-1

I'm making a UDP client/server program. The client collects data and sends it to the server.

The client sends a datagram with a random port number to the server on a specific UDP port 6789. The client and server then use the random port to share information.

The problem I have is that only one client can connect. I feel that it is because port 6789 never gets reopened for the next client.

This is the code just for the server receiving the initial connection on port 6789.

public class MonitorServer extends Thread{

    public static void main(String[] args) {

try{

    DatagramSocket connectSocket = new DatagramSocket(6789);     
    while( true )
    {
            String portString = "";
            int portInt = 0;
            byte [] buffer = new byte[100];

System.out.println("portTest 01 " +portInt);
            DatagramPacket portPacket = new DatagramPacket(buffer, buffer.length);
            connectSocket.receive(portPacket);
            portString = new String (portPacket.getData());
            connectSocket.disconnect();  
            connectSocket.close();

System.out.println("portTest 02 " +portString);
            portString = portString.replaceAll("[^0-9.,]+","");
            portInt = Integer.parseInt(portString);

System.out.println("portTest 03 " +portString);                    
            ClientConnection c = new ClientConnection(portInt);
            new Thread(c).start();

System.out.println("portTest 04 " +portString); //<<-- never prints
   }
  }

  catch (Exception e) {}
 }

}

It seems like this section of code only runs once. I added System.outs to troubleshoot and it looks like it stops at:

            ClientConnection c = new ClientConnection(portInt);
            new Thread(c).start();

System.out.println("portTest 04 ");  //<-- Never prints

I need it to keep running to accept connections. What am I doing wrong?

4

2 回答 2

0

在您的代码中,MonitorServer.startServer 方法永远不会返回,因为它进入了无限的 while 循环。这意味着MonitorServer' 的构造函数永远不会返回,这意味着 main 中的 while 循环永远不会到达关闭并且永远不会循环。你需要从MonitorServer一个新的ThreadExecutor Service

于 2012-04-22T20:29:38.380 回答
0

您应该在接收循环之外在 5678 上创建一次套接字。不是每次收到。

注意,UDP 中没有“connectig”之类的东西,除了 DatagramSocket.connect() 所做的有限的事情,这是对等方不知道的。

于 2012-04-22T23:06:00.073 回答