[英]Socket Server accepting only one connection at a time on the same process
我正在嘗試實現一個客戶端服務器應用程序,其中服務器可以從客戶端接受一些對象,並且對於每個對象,它必須將其解釋為消息並正確處理。
這是代碼:
(服務器)
public class GlobalServer{
GlobalServer(){new Thread(() ->{
try {
serverSocket = new ServerSocket(1234);
Socket clientSocket;
while (true) {
clientSocket = serverSocket.accept();
handleClient(clientSocket);
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}).start();
}
public void handleClient(Socket clientSocket) throws IOException, ClassNotFoundException{
ObjectInputStream is = new ObjectInputStream(clientSocket.getInputStream());
Object [] objArr = (Object[]) is.readObject();
msgHandler(objArr, clientSocket);
}
public void msgHandler(Object [] objArr, Socket clientSocket){
int msg_type = (int) objArr[0];
switch (msg_type) {
case 1:
System.out.println("type 1 received");
break;
case 2:
System.out.println("type 2 received");
break;
case 3:
System.out.println("type 3 received");
break;
default:
break;
}
}
public static void main(String [] args){
GlobalServer s = new GlobalServer();
}
}
OBS:在應用程序上,有意義的是接收對象數組,因為每個消息都帶有其標頭(類型)及其內容
(客戶)
public class Client {
public static void main(String [] args){
try {
Socket client = new Socket("192.168.0.105", 1234);
ObjectOutputStream os = new ObjectOutputStream(client.getOutputStream());
Object [] objArr = {3, "Type 3 message"};
os.writeObject(objArr);
Object []objArr1 = {1, "Type 1 message"};
os.writeObject(objArr1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我在單獨的計算機上運行GlobalServer的實例,然后在連接到服務器的另一台計算機上運行,並順序發送兩個消息。 問題在於服務器僅接收和處理第一條消息,第二條消息丟失,並且客戶端完成而服務器沒有收到第二條消息。 奇怪的是,如果我將這兩個messagens作為兩個不同的應用發送,則服務器會很好地處理它。 這與在同一過程中發送的兩個消息蜂有關嗎?
代碼用作不同的應用程序:
(消息1)
public class Message1 {
public static void main(String [] args){
try {
Socket client = new Socket("192.168.0.105", 1234);
ObjectOutputStream os = new ObjectOutputStream(client.getOutputStream());
Object [] objArr = {3, "Type 3 message"};
os.writeObject(objArr);
} catch (IOException e) {
e.printStackTrace();
}
}
}
(消息2)
public class Message2 {
public static void main(String [] args){
try {
Socket client = new Socket("192.168.0.105", 1234);
ObjectOutputStream os = new ObjectOutputStream(client.getOutputStream());
Object []objArr1 = {1, "Type 1 message"};
os.writeObject(objArr1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
問題在以下代碼塊中:
public void handleClient(Socket clientSocket) throws IOException, ClassNotFoundException{
ObjectInputStream is = new ObjectInputStream(clientSocket.getInputStream());
Object [] objArr = (Object[]) is.readObject();
msgHandler(objArr, clientSocket);
}
您僅讀取一個對象。 (Object[]) is.readObject();
為了讀取多個對象並為每個對象調用msgHandler
方法,應在循環中調用該方法。
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.