wp7:msdn上的socket类,改写后发现问题,求解决
客户端的socket类的来源在这里
http://msdn.microsoft.com/zh-cn/library/hh202858(v=VS.92).aspx#Y3648
msdn上的代码只是进行一次客户端的连接、发送、接收数据,然后就断开了,根据需要,我把主页面程序里修改成一次连接、但不马上中断连接,可以持续进行收发数据。类的代码没有修改。然后调试发现,在调用类的receive函数时,偶尔会发生离奇的事情。表现在:有时候接收到数据,触发receive里的完成事件时,明明把接收到的数据放在stirng类型的response 变量里,然后set信号量状态,再跳转到函数最后一行,准备执行 return response时,竟然发现response 为空字符串了!
查了一些资料,发现可能是在完成事件的回调中,发生了线程重入的事,导致了变量response 值被修改了。作为c#,WP初学者,想请教如何解决这个问题,或者有更好地socket类可以解决这个问题吗?
另外,这个“偶尔”的现场在这种情况下会出现。调用receive函数后,服务端没有发送数据,然后执行 _clientDone.WaitOne(TIMEOUT_MILLISECONDS) ,没有触发任何socket完成事件后,因超时而结束阻塞,结束receive函数后,再一次执行receive,这时服务端发送了数据,虽然触发了socket事件,可以接收到数据,但是 return response 时,还是返回空值。
附上SocketClient::receive函数
public string Receive() { string response = ""; // 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) { // Retrieve the data from the buffer response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred); response = response.Trim('\0'); } 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; }