我假設你正在使用TCP套接字進行客戶端 - 服務器交互?一種將不同類型的數據發送到服務器並且能夠區分這兩種數據的方法是將第一個字節(或者如果有超過256種類型的消息)專用作某種標識符。如果第一個字節是一個,那麼它是消息A,如果2,然後它的消息B.一個簡單的方法來發送這個在插座是使用DataOutputStream/DataInputStream
:
客戶:
Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data
// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data
// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data
// Send the exit message
dOut.writeByte(-1);
dOut.flush();
dOut.close();
服務器:
Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());
boolean done = false;
while(!done) {
byte messageType = dIn.readByte();
switch(messageType)
{
case 1: // Type A
System.out.println("Message A: " + dIn.readUTF());
break;
case 2: // Type B
System.out.println("Message B: " + dIn.readUTF());
break;
case 3: // Type C
System.out.println("Message C [1]: " + dIn.readUTF());
System.out.println("Message C [2]: " + dIn.readUTF());
break;
default:
done = true;
}
}
dIn.close();
顯然,您可以發送各種數據,而不僅僅是字節和字符串(UTF)。
Thankyou,這讓我前往在正確的方向! – 2011-04-15 19:34:15