這是有點困惑你在說什麼,或者,可能需要更多的信息。請記住,UDP客戶端不會連接它們只是發送數據包,並且這些數據包不能保證按照它們發送的順序到達。
我會做的只是有一個偵聽UDP套接字等待數據包。您應該通過其IP地址或任何其他方法(例如數據包數據中的ID)來維護有效客戶端的列表。一旦接收到數據包,您就可以使用處理客戶端請求的函數/線程來處理數據包。正如我所看到的,您甚至不需要啓動新線程,但它取決於接收數據包時服務器將執行的操作以及處理該數據包需要多長時間。此外,請記住,處理請求的函數/線程無法從客戶端接收更多數據包(通過同一端口);所有傳入的數據包都由服務器線程傳遞。處理客戶端請求的函數或線程只需要向客戶端發送一個或多個UDP數據包來確認請求,但它不能與客戶端保持對話,也不能確定客戶端是否因爲沒有永久的開放連接。如果您需要服務器和客戶端之間的對話,則需要更改爲TCP套接字。
這是一個代碼草案:
ClientRequestThread(DatagramPacket packet)
{
String FromIP = packet.getAddress().getHostAddress();
byte[] data = packet.getData();
// Here you must identify the client, either by its IP address
// or maybe an ID inside the data.
if (TheDataHaveBeenProccessOK)
{
Send a positive acknowledge
}
else
{
Send a negative acknowledge
}
}
ServerThread()
{
DatagramSocket datagramSocket;
try
{
datagramSocket = new DatagramSocket(MyPortNumber);
}
catch (Exception e)
{
// Unable to open the datagram socket.
// Handle it accordingly
return;
}
byte[] buffer = new byte[256]; // change it to your needs
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (YouDontStopMe)
{
try
{
datagramSocket.receive(packet);
// Here you must either call a function or start a thread
// to handle the client request
// depends on what you are going to do with the client's request.
ClientRequestThread(packet);
}
catch (Exception e)
{
// Error reading the socket, handle it accordingly
e.printStackTrace();
}
}
datagramSocket.close();
}