我正在尝试在java中执行 UDP多线程回显服务器和客户端 目前我有UDP echo服务器和客户端,但没有多线程部分 这是我的代码:
服务器:
import java.io.*;
import java.net.*;
class EchoServer implements Runnable
{
protected static DatagramSocket serverSocket;
protected byte[] receiveData = new byte[1024];
protected byte[] sendData = new byte[1024];
public EchoServer() throws SocketException{
this.serverSocket = new DatagramSocket(9876);
}
public void run() {
try {
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);
}
} catch (IOException e) {
//report exception somewhere.
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception
{
EchoServer ES = new EchoServer();
ES.run();
}
}
客户端:
import java.io.*;
import java.net.*;
class EchoClient
{
public static void main(String args[]) throws Exception
{
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, 9876);
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();
}
}
如何将其转为多线程? 谢谢:))