简体   繁体   English

C#中的Socket通信中消息太长错误

[英]Message too long error in Socket communication in C#

When I use sendto() to send messages, i get the error "message too long"? 当我使用sendto()发送消息时,出现错误“消息太长”吗?

 Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

How can I find out the maximum possible size that i can send? 如何找到可以发送的最大尺寸? Can I change it? 我可以改变吗? What could be possible problem here? 这里可能有什么问题?

First of all, SendTo is only used for UDP sockets. 首先, SendTo仅用于UDP套接字。 In the code snippet above, you are opening a TCP socket. 在上面的代码段中,您正在打开一个TCP套接字。 SendTo won't work with a TCP socket. SendTo不适用于TCP套接字。 Try it with a UDP socket and see if it works. 尝试使用UDP套接字,看看是否可行。 Bear in mind that the maximum practical size of a UDP packet is 65,507 bytes. 请记住,UDP数据包的最大实际大小为65,507字节。 Generally, you want to keep UDP packets small to avoid fragmentation by the various network elements involved with their transmission. 通常,您希望将UDP数据包保持较小,以避免与传输有关的各种网络元素造成碎片。

EDIT: 编辑:

Use TcpClient to make your life easier. 使用TcpClient使您的生活更轻松。

Int32  port = 13293;
String host = "somehost.com";
TcpClient tcpClient = new TcpClient(host, port);

Byte[] data = System.Text.Encoding.ASCII.GetBytes("your message to send");

NetworkStream stream = tcpClient.GetStream();

stream.Write(data, 0, data.Length);

From the Linux man pages for socket(), you should be able to use the sysctls(2) or /proc/sys/net/core/* files. 从Linux的socket()手册页中,您应该能够使用sysctls(2)或/ proc / sys / net / core / *文件。 I think in particular you could use the following: 我认为您尤其可以使用以下内容:

rmem_default rmem_default
contains the default setting in bytes of the socket receive buffer. 包含套接字接收缓冲区的默认设置(以字节为单位)。
rmem_max rmem_max
contains the maximum socket receive buffer size in bytes which a user may set by using the SO_RCVBUF socket option. 包含用户可以通过使用SO_RCVBUF套接字选项设置的最大套接字接收缓冲区大小(以字节为单位)。

  • Use the first one to check what the default size is for the receive buffer. 使用第一个检查接收缓冲区的默认大小。
  • Look at the second one to determine maximum size and ensure the size of the packets you are sending are less than that. 查看第二个,以确定最大大小,并确保要发送的数据包的大小小于该大小。
  • Use the SO_RCVBUF socket option to change the size of the receive buffer. 使用SO_RCVBUF套接字选项可以更改接收缓冲区的大小。

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

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