我假设你正在使用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