Socket tcp c#如何清除输入缓冲区
本文关键字:清除 输入 缓冲区 tcp 何清除 Socket | 更新日期: 2023-09-27 18:14:57
我正在为windows phone编写一个应用程序,我需要与服务器通信并传输数据。SERVER是用c++写的,我不能修改它。客户是我必须写的东西。服务器被设计成客户端连接到它并传输数据。该连接对所有传输保持打开状态。通过用c#编写代码,我能够从服务器接收数据,但在第一次接收之后,我在缓冲区中读取的数据总是相同的。所以我需要一种方法来刷新输入缓冲区,这样我就可以接收新的数据(数据是连续发送的)。我使用这里定义的类:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202858%28v=vs.105%29.aspx非常感谢!
我在SocketClient.cs中使用了以下代码:
public string Receive()
{
string response = "Operation Timeout";
// We are receiving over an established socket connection
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
// Setup the buffer to receive the data
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
// Inline event handler for the Completed event.
// Note: This even handler was implemented inline in order to make
// this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// *********************************************
// THIS part of the code was added to receive
// a vector of 3 double
Double[] OdomD = new Double[3];
for (int i = 0; i < 3; i++)
{
OdomD[i] = BitConverter.ToDouble(e.Buffer, 8 * i);
}
// *********************************************
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Receive request over the socket
_socket.ReceiveAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
Connect()方法与上面链接中报告的方法完全相同。因此,当应用程序启动时,Connect()方法被如下调用:
SocketClient client = new SocketClient();
// Attempt to connect to server for receiving data
Log(String.Format("Connecting to server '{0}' over port {1} (data) ...", txtRemoteHost.Text, 4444), true);
result = client.Connect(txtRemoteHost.Text, 4444);
Log(result, false);
在开始时只做一次,然后我需要接收这个每秒更新一次的3 double数组。所以我使用:
Log("Requesting Receive ...", true);
result = client.Receive();
Log(result, false);
问题是,如果我调试代码并停止Receive()内的执行,我总是读取相同的值,这是服务器发送的第一个值。我所期望的是,每次调用client.Receive()时,我都会得到新的值,但这并没有发生。
我在Matlab环境中编写相同的客户端时遇到了类似的问题。我通过使用函数flushinput(t)之前读取输入缓冲区解决了这个问题。通过这种方式,我总是能够读取服务器发送的最后一个数据。我正在寻找一个类似的功能…
输入缓冲区的大小固定等于我期望接收的数据,在这种情况下是24字节(3* sizeof(double)) .
非常感谢你的时间!!oleksii是对的,您应该在循环中调用client.Receive()。您可以选择启动一个覆盖代码接收部分的线程。还要注意,client.Receive()将继续尝试从缓冲区接收,如果没有可用的数据,它将卡住。
主要问题是**如何清除输入缓冲区?**还是我错了?
不过;因为你没有固定的缓冲区,从你发布的代码中可以看到,并通过SocketAsyncEventArgs
接收它,你可以用:
Array.Clear(e.Buffer, 0, e.Buffer.Length);