简体   繁体   English

为自定义TCP协议实现客户端

[英]Implementing a client for custom TCP protocol

I have to implement a client for communication with the server by custom protocol based on XML format. 我必须实现一个客户端,以便通过基于XML格式的自定义协议与服务器进行通信。 This is an application layer protocol, based on TCP . 这是基于TCP的应用程序层协议。 So, my client sends a request XML message and receives a response, also XML message. 因此,我的客户发送请求XML消息并接收响应,也就是XML消息。 Now, I consider how to be ensured that I received whole mesage before I start parsing it. 现在,我考虑如何确保在开始解析之前收到完整的消息。

I see two aproaches: 我看到两个方法:

  1. Receiving bytes to the some magic number that means end of message. 接收字节到某个魔术数字,这意味着消息结束。 It is the best approch (for my eye), yes? 对我来说,这是最好的方法,是吗?

  2. But, it is possible that there is no magic number and size of message is not known. 但是,可能没有幻数,消息大小未知。 What about that case? 那情况呢? I saw some clients for other protocols and I see something like that. 我看到了一些其他协议的客户端,并且看到了类似的东西。

     while(true){ r = socket.read(buffer, offset, 1024); if(r < 1024) break; offset += r; } // parse buffer 

and I am not sure whether it is ok. 而且我不确定是否还可以。 It assumes that if we read less than 1024 bytes then the messae is completed. 假定如果我们读取的字节数少于1024个字节,则该消息已完成。 Is it ok? 可以吗

What is a recommend way to solve it? 有什么推荐的解决方法?

In your custom protocol you need to include the steps below : 在您的自定义协议中,您需要包括以下步骤:

Client 客户

  1. Calculate number of 1024 byte chunks of the XML contents ie ceiling(XML content bytes /1024) 计算XML内容(即上限)的1024个字节块的数量(XML内容字节/ 1024)
  2. Send the number of step 1 to the server through the socket 通过套接字将步骤1的编号发送到服务器
  3. Transmit the contents in chunks of a defined buffer size eg 1024 bytes 以定义的缓冲区大小(例如1024字节)的块形式传输内容

Server 服务器

  1. Read number of chunks to receive from client 读取要从客户端接收的块数

  2. Inside a for loop of size equal to the number read at step 1, start receiving contents in the predifined buffer size. 在大小等于在步骤1读取的数字的for循环内,开始接收预定义缓冲区大小的内容。

This way the server knows how many bytes the actual content is before it starts receiving the XML contents. 这样,服务器在开始接收XML内容之前便知道实际内容有多少字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM