我试图为服务编写服务器和客户端,这将告诉当前时间。我的代码:
服务器
public class TimeServer {
public static void main(String[] args) {
try {
final DatagramSocket so = new DatagramSocket(8189);
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
try {
InetAddress group = InetAddress.getByName("200.20.2.0");
byte[] buf = new byte[256];
Calendar cal = Calendar.getInstance();
buf = cal.toString().getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length,
group, 8189);
so.send(packet);
} catch (IOException ex) {
ex.printStackTrace();
}
Thread.sleep((int)(Math.random() * 5));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}).start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
客户
public class TimeClient {
public static void main(String[] args) {
try {
MulticastSocket so = new MulticastSocket(8190);
InetAddress group = InetAddress.getByName("200.20.2.0");
so.joinGroup(group);
//5 razy czekamy na otrzymanie od serwera wiadomosci
for (int a=0; a<5; a++) {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
so.receive(packet);
String recv = new String(packet.getData());
System.out.println("RECEIVED: " + recv);
}
so.leaveGroup(group);
so.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
启动服务器然后启动客户端时,出现以下错误:
java.net.BindException: Address already in use
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:95)
at java.net.DatagramSocket.bind(DatagramSocket.java:376)
at java.net.MulticastSocket.<init>(MulticastSocket.java:172)
at java.net.MulticastSocket.<init>(MulticastSocket.java:137)
at timeclient.TimeClient.main(TimeClient.java:13)
请帮忙,谢谢
编辑: 我更改了客户端端口,现在出现异常:
java.net.SocketException: Not a multicast address
at java.net.MulticastSocket.joinGroup(MulticastSocket.java:306)
at timeclient.TimeClient.main(TimeClient.java:15)
现在做什么?