我正在为 windows phone 编写应用程序,我需要与服务器通信并传输数据。服务器是用 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 个双精度数组。所以我使用:
Log("Requesting Receive ...", true);
result = client.Receive();
Log(result, false);
问题是,如果我在 Receive() 中调试代码并停止执行,我总是读取相同的值,即服务器发送的第一个值。我所期待的是,每次我调用 client.Receive() 时,我都会得到新的值,但这并没有出现。
通过在 Matlab 环境中编写相同的客户端,我遇到了类似的问题。我通过在读取输入缓冲区之前使用函数 flushinput(t) 解决了这个问题。通过这种方式,我能够始终读取服务器发送的最后一个数据。我正在寻找与那个类似的功能..
输入缓冲区的大小固定等于我期望接收的数据,在这种情况下是 24 字节( 3* sizeof(double) )..
非常感谢您的时间!