我做了一個UDP服務器客戶端體系結構與多線程問題是當我從服務器發送到客戶端另一個客戶端線程獲取數據包等所有..如何可以我指定UDP應該發回數據包的線程?多線程服務器和客戶端Java指定客戶端線程
Client
public UDPClient(int port) throws SocketException
{
this.socket = new DatagramSocket();
this.arg1 = (int) (Math.random() * 1000) ;
this.arg2 = (int) (Math.random() * 1000) ;
this.port = port ;
}
public void run()
{
try{
String x = arg1 + " + " + arg2;
BUFFER = x.getBytes();
InetAddress ip = InetAddress.getByName("127.0.0.1");
packet = new DatagramPacket(BUFFER , BUFFER.length,ip,port);
printOutput(new String("Client send" + x));
socket.send(packet);
socket.receive(packet);
String output = new String(packet.getData(),0,packet.getLength());
printOutput(new String("receive " + x + "=" + output));
}
catch(IOException e)
{
System.out.println("UDP sending problem " + e.getMessage());
}
}
服務器
public void run()
{
while(true)
{
try{
packet = new DatagramPacket(BUFFER,BUFFER.length);
socket.receive(packet);
executor.execute(new UDPServerCore(socket,packet,BUFFER));
}
catch(IOException e)
{
System.out.println("UDP receiving packet problem "
+ e.getMessage());
}
}
}
ServerCore
@Override
public void run(){
String x = new String(packet.getData(),0,packet.getLength());
String y = parseString(x);
BUFFER = y.getBytes();
//packet.setData(y.getBytes());
DatagramPacket res = new DatagramPacket(BUFFER , BUFFER.length
,packet.getAddress(),packet.getPort());
try{
socket.send(res);
}
catch(IOException e)
{
System.out.println("Something went wrong " + e.getMessage());
}
}
synchronized private static String parseString(String x)
{
String arr[] = x.split(" ");
int z = Integer.parseInt(arr[0]);
int y = Integer.parseInt(arr[2]);
y = y + z;
writeServer.append(x+ "=" + y +"\n");
return String.valueOf(y);
}
我解決它的問題是,當我創造了我應該先創建所有指定的端口,客戶端線程的線程的端口然後開始每個線程。
歡迎StackOverflow上檢索您的會話對象時!你能分享一些不起作用的代碼嗎? – andorov
爲什麼服務器上的每個「客戶端」都需要自己的線程? – WalterM
你是什麼意思'指定線程'?不清楚你在問什麼。 – EJP