Lon*_*ent 31 java sockets android
我使用套接字连接我的Android应用程序(客户端)和Java后端服务器.从客户端我想每次与服务器通信时发送两个数据变量.
1)某种消息(由用户通过界面定义)
2)消息的语言(由用户通过界面定义)
我怎么能发送这些,以便服务器将每个解释为一个单独的实体?
在服务器端读取数据并得出适当的结论后,我想向客户端返回一条消息.(我想我会好起来的)
所以我的两个问题是如何确定发送的两个字符串(客户端到服务器)在客户端是唯一的,如何在服务器端分离这两个字符串.(我正在考虑一系列字符串,但无法确定这是否可行或适当.)
我打算发布一些代码,但我不确定这会有什么帮助.
Nic*_*nks 62
我假设你使用TCP套接字进行客户端 - 服务器交互?将不同类型的数据发送到服务器并使其能够区分这两者的一种方法是将第一个字节(或更多,如果您有超过256种类型的消息)专用于某种标识符.如果第一个字节是1,那么它是消息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();
Run Code Online (Sandbox Code Playgroud)
服务器:
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();
Run Code Online (Sandbox Code Playgroud)
显然,您可以发送各种数据,而不仅仅是字节和字符串(UTF).
请注意,writeUTF写入修改后的UTF-8格式,前面是无符号双字节编码整数的长度指示符,给出2^16 - 1 = 65535要发送的字节.这使得可以readUTF找到编码字符串的结尾.如果您决定自己的记录结构,那么您应该确保记录的结尾和类型是已知的或可检测的.
最简单的方法是将您的套接字包装在 ObjectInput/OutputStreams 中并发送序列化的 java 对象。您可以创建包含相关数据的类,然后您无需担心处理二进制协议的具体细节。只需确保在编写每个对象“消息”后刷新对象流。
| 归档时间: |
|
| 查看次数: |
119153 次 |
| 最近记录: |