我在服务器和客户端之间建立了正确的连接,我从客户端向服务器发送消息,但是我如何从服务器向客户端发送消息。我的意思是我怎样才能让服务器也像客户端一样。我试图将客户端方法复制到服务器可以调用的另一个类。但是我不能然后我尝试创建一个新包来使用服务器类中的客户端代码。有什么建议吗?
ps:对不起我的英语。
public class Entrance_Server extends JFrame{
JButton buton = new JButton("Create");
JButton buton2 = new JButton("Join");
JPanel butonpanel = new JPanel();
DatagramSocket sockServer = null;
DatagramSocket sockClient = null;
int port = 7777;
String s;
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
public Entrance_Server() {
setLayout(new GridLayout(2,1));
add(buton);
add(buton2);
buton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Choosing c = new Choosing();
c.start();
System.out.println("Server socket created. Waiting for incoming data...");
}
});
buton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Choosing c = new Choosing();
c.start();
}
});
}
public static void main(String[] args){
Entrance_Server e = new Entrance_Server();
e.setSize(500,350);
e.setTitle("Welcome");
e.setLocationRelativeTo(null);
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
e.setVisible(true);
e.connect();
}
public void connect (){
try{
sockServer = new DatagramSocket(7777);
byte[] buffer = new byte[65536];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
while(true)
{
sockServer.receive(incoming);
byte[] data = incoming.getData();
String s = new String(data, 0, incoming.getLength());
//echo the details of incoming data - client ip : client port - client message
System.out.println(incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " - " + s);
s = "OK : " + s;
DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , incoming.getPort());
sockServer.send(dp);
Entrance_Client_in_Server ec = new Entrance_Client_in_Server();
ec.connectc();
}
}catch(IOException i){
System.err.println("IOException " + i);
}
}
}