这是我第一次在 java 中编写客户端-服务器或更准确地说是套接字编程。 我正在创建一个提供一些端口的服务器。现在在同一个系统中,我启动了一些客户端窗口,当我从客户端发送任何消息时,它会通过服务器广播到每个客户端。现在,如果我在不同系统中通过 LAN 运行相同的服务器代码,问题就不会发生。 数据没有被广播。以下是我的服务器代码-
public void run() {
try {
serverSocket = new DatagramSocket(9878);
group = InetAddress.getByName("230.0.0.1");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
while (true) {
try {
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
receiveData = receivePacket.getData();
if (receivePacket.getLength() > 0) {
String sentence = new String(receivePacket.getData());
DatagramPacket packet = new DatagramPacket(sendData,
sendData.length, group, 9879);
serverSocket.send(packet);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
现在我的客户正在通过 -
private final void sendDatatoServer(){
IPAddress = InetAddress.getByName("localhost");
String sentence = strTitle+" : "+textPane.getText();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9878);
textPane.setText("");
try {
clientSocket.send(sendPacket);
} catch (IOException e1) {
e1.printStackTrace();
}
}
我再次像这样从服务器读取广播数据-
try {
address = InetAddress.getByName("230.0.0.1");
socket = new MulticastSocket(9879);
socket.joinGroup(address);
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runnableTask = backgroundExec.submit(new Runnable() {
@Override
public void run() {
while(true){
try {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
setEditor(received);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});