UDP服务器中的多个客户端

时间:2014-01-25 20:10:53

标签: java sockets udp

我编写了这段代码,通过socket

从客户端中恢复数据
import java.io.*;
import java.net.*;

class UDPServer
{
   public static void main(String args[]) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(12890);
            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());
                  System.out.println("RECEIVED: " + 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);
               }
      }
} 

但是,如果我尝试启动另一个客户端它不起作用,看起来好像服务器被阻止了。如何更改代码以使服务器与多个客户端进行通信

1 个答案:

答案 0 :(得分:0)

您正在寻找并发服务器。并发服务器基本上为每个客户端创建子进程。这是java http://www.how2java.com/2012/05/how-to-create-concurrent-server-using.html

中的基本方法