Java中的UDP线程无限循环

| 我已经写了两个程序。现在,每个程序都使用线程来同时发送和接收数据包。 每当我从服务器向客户端发送数据包时,客户端的消息就会在无限循环中被接收。即我添加了一条打印语句,该语句打印已发送的消息,并且此语句永远处于无限循环中。我要使其接收消息,然后能够写回到服务器,并在用户需要时退出。 我尝试使用socket.close(),但是这样做可以使客户端收到消息,而我只能写回服务器一次。发送后,我无法发送了。我想这样做,以便我可以多次写回信。 谁能指出我正确的方向? 我的代码如下:
public class UDPThreadClient extends Thread {

public static int port1;

//Create threaded server
UDPThreadClient (int port1) {
    System.out.println (\"Starting threaded client\");
    start();
}

public void run() {

    int port = port1;

    try {
        DatagramSocket serverSocket = new DatagramSocket(port1);
           byte[] receiveData = new byte[1024];
           byte[] sendData = new byte[1024];

           while (true) { 
                 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                 serverSocket.receive(receivePacket);
                 String sentence = new String( receivePacket.getData());
                 SocketAddress address = receivePacket.getSocketAddress();


                 System.out.println(\"RECEIVED from \" + address + \" : \" + sentence);

                 InetAddress IPAddress = receivePacket.getAddress();
                 //int port = receivePacket.getPort();
                 String capitalizedSentence = sentence.toUpperCase();
                 sendData = capitalizedSentence.getBytes();
                 DatagramPacket sendPacket =
                 new DatagramPacket(sendData, sendData.length, IPAddress, port);
                 serverSocket.send(sendPacket);
                 //serverSocket.close();
           }  
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }

}

//Create client
public static void main(String[] args) {

    int port = Integer.parseInt(args[0]);
    port1 = Integer.parseInt(args[1]);
    new UDPThreadClient (port1);
    try {

          BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

          DatagramSocket clientSocket = new DatagramSocket();
          InetAddress IPAddress = InetAddress.getByName(\"localhost\");

          byte[] sendData = new byte[1024];
          byte[] receiveData = new byte[1024];

          String sentence = inFromUser.readLine();

          sendData = sentence.getBytes();

          DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

          clientSocket.send(sendPacket);

          DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

          clientSocket.receive(receivePacket);

          String modifiedSentence = new String(receivePacket.getData());

          System.out.println(\"FROM SERVER:\" + modifiedSentence);

         //clientSocket.close();
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }
}
   }
public class UDPThreadServer extends Thread {

public static int port1;

//Create threaded client
UDPThreadServer () {

    System.out.println (\"Starting threaded server\");
    start();


}

public void run() {

    try {
        DatagramSocket clientSocket = new DatagramSocket();

            BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
            Scanner in = new Scanner (inFromUser);
            InetAddress IPAddress = InetAddress.getByName(\"localhost\");
        byte[] sendData = new byte [1024];
        byte[] receiveData = new byte [1024];

        while (in.hasNextLine()) {
        String sentence = in.nextLine();
        //inFromUser.readLine();
        sendData = sentence.getBytes();

        DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port1);
        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length);
        clientSocket.receive (receivePacket);

        String modSentence = new String (receivePacket.getData());
        System.out.println (\"FROM SERVER: \" + modSentence);
        }
        //clientSocket.close();
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }

}

//Create server
public static void main(String[] args) {

    int port = Integer.parseInt(args[0]);
    port1 = Integer.parseInt(args[1]);
    new UDPThreadServer ();
    try {
        DatagramSocket serverSocket = new DatagramSocket (port);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];

        while (true) {
            DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            String sentence = new String(receivePacket.getData());
            SocketAddress address = receivePacket.getSocketAddress();
            System.out.println (\"Received from \" + address + \" : \" + sentence);

            InetAddress IPAddress = receivePacket.getAddress();
            String capSentence = sentence.toUpperCase();
            sendData = capSentence.getBytes();
            DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port);
            serverSocket.send(sendPacket);
            //serverSocket.close();
        }

    } catch (IOException e) {
        System.out.println (e.getMessage());
    }
}

}
谢谢。     
已邀请:
        查看UDPClientServer: 创建数据报数据包时,您给它提供了发送数据包的端口,而不是发送它的端口。 当我运行您的代码时,什么都没发生。服务器正在端口
port
上等待,而客户端发送到端口
port1
。如果改为发送到端口
port
(不能从main方法访问,而是将其更改为字段而不是local方法可以解决此问题,则将发生无限循环,因为服务器将数据包发送到正在侦听的同一端口。问题是您在程序中提供的数字与第一个和第二个参数相同吗? 在服务器上,您可以使用
receivePacket.getPort()
获取数据包来自的端口。 编辑: 您的两个班级重复很多,这很可能造成混乱。一类有一个主程序,该主程序启动客户端,然后创建服务器类型循环测试器。另一个类设置服务器,然后创建客户端类型测试器。 下面仅是您已命名为UDPThreadServer的类,并带有注释,该注释显示了使服务器“工作”到主方法中的测试代码的更改。请注意,服务器应将其发送到未监听的端口。您还将从命令行参数读取端口值。我只是为端口计算了一些数字,并将其作为常量插入。
public class UDPThreadServer extends Thread
{

  public static int port1;

  UDPThreadServer()
  {
    //server or client?  it\'s hard to say.  you call the socket a clientSocket.
    System.out.println(\"Starting threaded server\");
    start();
  }

  public void run()
  {
    try
    {
      // Here client(?) is set up with empty constructor.
      // It is a mystery what port it will get.
      DatagramSocket clientSocket = new DatagramSocket();

      BufferedReader inFromUser =
          new BufferedReader(new InputStreamReader(System.in));
      Scanner in = new Scanner(inFromUser);
      InetAddress IPAddress = InetAddress.getByName(\"localhost\");
      byte[] sendData = new byte[1024];
      byte[] receiveData = new byte[1024];

      while (in.hasNextLine())
      {
        String sentence = in.nextLine();
        // inFromUser.readLine();
        sendData = sentence.getBytes();

        // sending to port1?  that must be the server.
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, port1);
        clientSocket.send(sendPacket);

        DatagramPacket receivePacket =
            new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);

        String modSentence = new String(receivePacket.getData());
        System.out.println(\"FROM SERVER: \" + modSentence);
      }
      // clientSocket.close();
    } catch (IOException e)
    {
      System.out.println(e.getMessage());
    }
  }

  // Create server
  public static void main(String[] args)
  {

    // int port = Integer.parseInt(args[0]);
    int port = 1927; // or whatever
    // port1 = Integer.parseInt(args[1]);
    port1 = 1928;
    new UDPThreadServer();
    try
    {
      // server resides on port1?  if client sends to port 1, then this is so.
      DatagramSocket serverSocket = new DatagramSocket(port1);
      byte[] receiveData = new byte[1024];
      byte[] sendData = new byte[1024];

      while (true)
      {
        DatagramPacket receivePacket =
            new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        String sentence = new String(receivePacket.getData());
        SocketAddress address = receivePacket.getSocketAddress();
        System.out.println(\"Received from \" + address + \" : \" + sentence);

        InetAddress IPAddress = receivePacket.getAddress();
        String capSentence = sentence.toUpperCase();
        sendData = capSentence.getBytes();

        // where did you get the info from?  Client is set up with an empty constructor, so it is a mystery.
        port = receivePacket.getPort();

        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, port);
        serverSocket.send(sendPacket);
        // serverSocket.close();
      }

    } catch (IOException e)
    {
      System.out.println(e.getMessage());
    }
  }
}
    
        不要关闭插座。 如果那不能回答您的问题,则需要进行澄清。     
        
while(true)
是无限循环。您是否退出了?     

要回复问题请先登录注册