java - 使用 Sockets 发送和接收数据

标签 java android sockets

我正在使用套接字连接我的 Android 应用程序(客户端)和 Java 后端服务器。每次与服务器通信时,我想从客户端发送两个数据变量。

1) 某种消息(由用户通过界面定义)

2) 消息的语言(由用户通过界面定义)

我如何发送这些以便服务器将它们解释为一个单独的实体?

在读取服务器端的数据并做出适当的结论后,我想向客户端返回一条消息。 (我想我会没事的)

所以我的两个问题是如何确定正在发送的两个字符串(客户端到服务器)在客户端是唯一的,以及如何在服务器端分离这两个字符串。 (我在想一个字符串数组,但无法确定这是否可行或合适。)

我打算发布一些代码,但我不确定这会有什么帮助。

最佳答案

我假设您正在使用 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();

服务器:

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)。

请注意,writeUTF 写入修改后的 UTF-8 格式,前面是无符号的两字节编码整数的长度指示符,为您提供 2^16 - 1 = 65535 字节发送。这使得 readUTF 可以找到编码字符串的结尾。如果您决定自己的记录结构,那么您应该确保记录的结尾和类型是已知的或可检测的。

关于java - 使用 Sockets 发送和接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5680259/

相关文章:

c++ - 如何在 TCP 监听器中处理异步发送和接收

python 套接字应用程序未按预期从终端运行

RestTemplate 和 RetryTemplate 的 JAVA Mockito 单元测试

java - 操作栏中缺少搜索操作项

android - 以字符计数的计时器

java - 我可以使用什么适配器来填充接受来自 Firestore 的多个查询的 recyclerView?

java - Android 比较两个微调器和新 Activity 的 Intent

java - 在 Android 中合并两个/多个图像(小部件)

android - 以编程方式向特定联系人发送文本(whatsapp)

c - 使用 select 和 recv 通过套接字从 Web 服务器获取文件