我编写了这段代码,通过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);
}
}
}
但是,如果我尝试启动另一个客户端它不起作用,看起来好像服务器被阻止了。如何更改代码以使服务器与多个客户端进行通信
答案 0 :(得分:0)
您正在寻找并发服务器。并发服务器基本上为每个客户端创建子进程。这是java http://www.how2java.com/2012/05/how-to-create-concurrent-server-using.html
中的基本方法