0

我试图为服务编写服务器和客户端,这将告诉当前时间。我的代码:

服务器

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)

现在做什么?

4

3 回答 3

1

每个端口只能由单个应用程序使用。在您的情况下,您的服务器和客户端(2 个应用程序)正在尝试使用导致异常的相同端口。

要修复它,例如将客户端的端口从更改81898190

于 2013-04-06T14:23:43.707 回答
0

您必须更改客户端端口(或服务器端口),因为每个端口只能由单个进程使用。

于 2013-04-06T14:24:36.727 回答
0

试试看DatagramSocket.setReuseAddress(true)会发生什么。

于 2013-04-06T15:03:29.000 回答