如何在不关闭套接字的情况下多次调用Socket Send和Receive?

时间:2022-03-21 20:54:08

I'm using the .NET Socket class.

我正在使用.NET Socket类。

Basically my program is to send XML commands via TCP to my server (running some 3rd party services), and it will send back an XML response.

基本上我的程序是通过TCP向我的服务器发送XML命令(运行一些第三方服务),它将发回一个XML响应。

What I wanted to do is to send and receive multiple times without closing the socket, because the server seems to slow down if I open and close the socket too many times in a short period of time.

我想要做的是在不关闭套接字的情况下多次发送和接收,因为如果我在短时间内打开和关闭套接字太多次,服务器似乎会变慢。

Stripped down version of my code:

剥离我的代码版本:

//Connects to server
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint("123.123.123.123", 8199);
socket.Connect(ipe);

//Send my message
int sent = sock.Send(buffer, buffer.Length, SocketFlags.None); //buffer contains my XML data

//Receives respond from server
byte[] buf = new byte[65536];
int ret = socket.Receive(buffer, 0, 65536, SocketFlags.None);

//Send my message again without closing the socket
sent = sock.Send(buffer, buffer.Length, SocketFlags.None); //buffer contains my XML data

//Receives respond from server failed..
ret = socket.Receive(buffer, 0, 65536, SocketFlags.None);

It send/receive works the first time, but not the second time. The second time it throws an exception "An existing connection was forcibly closed by the remote host". What do I need to do before I can issue another send/receive?

它发送/接收第一次工作,但不是第二次。第二次抛出异常“现有连接被远程主机强行关闭”。在我发出另一个发送/接收之前,我需要做什么?

Thank you so much for reading.

非常感谢您的阅读。

1 个解决方案

#1


1  

The problem might be these

问题可能是这些

  • other endpoint might have closed the connection
  • 其他端点可能已关闭连接

  • your Receive method is blocking since no data is sent by the other client
  • 您的Receive方法正在阻止,因为其他客户端没有发送任何数据

The server might have closed the connection since you might have a send an invalid packet. check whether the data you are sending is valid. Debug or have a tcp/ip packet montior in the server side and examine the packet you receive.

服务器可能已关闭连接,因为您可能发送了无效数据包。检查您发送的数据是否有效。在服务器端调试或使用tcp / ip数据包监视器并检查收到的数据包。

#1


1  

The problem might be these

问题可能是这些

  • other endpoint might have closed the connection
  • 其他端点可能已关闭连接

  • your Receive method is blocking since no data is sent by the other client
  • 您的Receive方法正在阻止,因为其他客户端没有发送任何数据

The server might have closed the connection since you might have a send an invalid packet. check whether the data you are sending is valid. Debug or have a tcp/ip packet montior in the server side and examine the packet you receive.

服务器可能已关闭连接,因为您可能发送了无效数据包。检查您发送的数据是否有效。在服务器端调试或使用tcp / ip数据包监视器并检查收到的数据包。