本文介绍了处理的WinRT StreamSocket断开(服务器和客户端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个应用程序,我写的Windows 8 / WinRT中使用该API StreamSocket做一个流连接到服务器。也就是说,服务器meta标签流数据到客户端,有时,而且可以随时断开连接。 我遇到的问题是,我有不知道什么时候该服务器已断开如何检测。似乎没有要上StreamSocket类中的任何事件或属性,无论是它的输入或输出流,或者有什么关系连接状态的DataReader / DataWriter类。 在此之上,DataReader的方法ReadAsync不从客户机服务器端断开之后失败。相反,操作,据我可以告诉成功,并填补到其缓冲区中的数据仅仅是过去的事情发送给它(即它不清除其内部缓冲区,即使我能看到它的服务器消费每次我叫ReadByte时间)的缓冲器。它这样做是要为每ReadAsync后续调用 - 加气站什么之前最后断开发送服务器的缓冲区。下面是代码的简化版本: 公共异步任务TestSocketConnectionAsync() {变种插座=新StreamSocket(); 等待socket.ConnectAsync(新的主机名(主机),Port.ToString(), SocketProtectionLevel.PlainSocket); 无功博士=新的DataReader(socket.InputStream); dr.InputStreamOptions = InputStreamOptions.Partial; this.cts =新CancellationTokenSource(); this.listenerOperation = StartListeningAsync(DR,CTS); } 公共异步任务StartListeningAsync(DataReader的博士,CancellationTokenSource CTS) { VAR令牌= cts.Token; ,而(真) { token.ThrowIfCancellationRequested(); VAR readOperation = dr.LoadAsync(1024); VAR的结果=等待readOperation; 如果(结果< = 0 || readOperation.Status = Windows.Foundation.AsyncStatus.Completed!) { cts.Cancel(); //不会被调用,状态始终已完成,结果总是大于0 } ,否则 {,而(dr.UnconsumedBufferLength大于0) {字节nextByte = dr.ReadByte(); // DriveStateMachine(nextByte); } } } } 解决方案 A "graceful" socket closure can be detected by the other side as a 0-length read. That is, it just acts like a regular end-of-stream.An "abortive" socket closure is more tricky. You have to send data to detect that the other side has closed, and once that write fails, any additional reads or writes should fail (with an exception). If your protocol doesn't permit you to send data, then you'll have to assume the connection is bad after a timeout expires and just close it. :(Depending on the application "abortive" socket closure may be normal - in particular, very busy servers may be written to clamp shut their connections because it allows them to reclaim resources more quickly (avoiding the four-step socket shutdown handshake).DataReader/DataWriter are not concerned with "connections." They're really just BitConverter, only designed better this time around.I would guess that the reason StreamSocket doesn't have a "connected" property is because Socket.Connected is nearly useless and definitely misleading.I would try using StreamSocket.InputStream.ReadAsync directly instead of using DataReader, since you are just reading bytes anyway. It sounds like you may have uncovered a bug in DataReader, which you should report on Microsoft Connect if InputStream.ReadAsync works as expected. Also see this related forum post. 这篇关于处理的WinRT StreamSocket断开(服务器和客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 07:11