我试图为服务编写服务器和客户端来告诉当前时间。我的代码:
服务器
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)
现在怎么办?
答案 0 :(得分:1)
每个端口只能由单个应用程序使用。在您的情况下,您的服务器和您的客户端(2个应用程序)正在尝试使用导致异常的相同端口。
要解决此问题,请将客户端的端口从8189
更改为8190
答案 1 :(得分:0)
您必须更改客户端端口(或服务器端口),因为每个端口只能由单个进程使用。
答案 2 :(得分:0)
尝试DatagramSocket.setReuseAddress(true)
,看看会发生什么。