使用TCP发送数据 [英] Send data using TCP

查看:300
本文介绍了使用TCP发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我正在Linux上使用C编写客户端和服务器程序.

我使用发送"命令发送消息,另一方面,我使用"recv"命令接收消息.问题是我要发送的消息中可能包含"\ 0"字符.接收到的此类消息将在第一个"\ 0"字符处截断.因此我无法收到全部消息.

我能做些什么?还有另一个命令可以解决我的问题吗?

谢谢!

Hello,

I am writing a client and server program using C on Linux.

I send a message with "send" command and on the other side I recieve the message with "recv" command. The problem is that the message that I want to send may contain ''\0'' characters inside it. Such messages when recieved are truncated at the first ''\0'' character. So I can not recieve the entire message.

What can I do? Is there another command that can solve my problem?

Thanks!

推荐答案

send()recv()绝对不会停在\ 0字符处,它们是正确使用的函数.如果没有看到源代码,很难提供帮助,问题可能出在客户端或服务器端.

也许看看您是否正在使用任何以0字符结尾的常规字符串处理功能,例如strlen() strcpy().您可以添加一些调试输出,以发送和接收多少字节.另请参见 Beej的网络编程指南 [
send() and recv() will definitely NOT stop at a \0 character and they are the right functions to use. Without seeing your source code it''s hard to help, the problem could be in the client or the server side.

Maybe have a look if you''re using any of the normal string handling functions that stop at 0 character, like strlen() or strcpy(). You could add some debugging output how much bytes you are sending and receiving. Also see Beej''s guide to networking programming[^], there are client/server examples in chapter 6.

Hope this helps. :)


据我所知,当收到第一个''\0''时,recv函数不会停止,因此问题出在您的代码中.如果必须在应用程序中处理可变长度的消息,然后将消息长度作为消息的(第一)部分发送,则接收方将能够要求提供完整的信息.
:)
As far as I know, the recv function does NOT stop when the first ''\0'' is received, hence the problem is in your code. If you must deal with variable length messages in your applications, then send the message length as (first) part of the message, this way the receiver will be able to ask for the whole info.
:)


使用TCP时,不能假定send()recv()中的数据块长度之间没有任何关系.您可能需要多个recv()调用才能从单个send()中获取数据,或者可能也很容易在单个recv()调用中获得多个send()数据.您必须继续拨打recv()直到收到完整的消息.
When using TCP you can''t assume any relation between data block lengths in send() and recv(). You may need multiple recv() calls to get the data from a single send() or you might just as well get multiple send() data in a single recv() call. You must keep calling recv() until you have received the whole message.


这篇关于使用TCP发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆