我用TCP/IP Socket 进行异步通信,代码从网上拷的,如下
线程
Private Sub Listen()
Dim strSend As String
Dim sTime As String
'Dim sMessage As String = Nothing
Try
tlTcpListen = New TcpListener(MyIPAdress, iPort)
tlTcpListen.Start()
tcClient = New TcpClient
tcClient = tlTcpListen.AcceptTcpClient()
Service_nsStream = tcClient.GetStream()
srRead = New StreamReader(Service_nsStream)
swWriter = New StreamWriter(Service_nsStream)
While True
Try
Dim sMessage As String = srRead.ReadLine
问题出在这一行,单步调试,首次srRead.ReadLine 为nothing,
下面的语句不执行,客户端发来的消息收不到,当从服务端向对方发送消息后,就能正常通信了,这个地方srRead.ReadLine 一直在等待中,导致阻塞了吗?还是什么原因?如果在vb.net教程这行之前向客户端任意发条消息也可以正常通信,但是总觉得c#教程这个方法不喜欢,有好的解决方案吗?
If Not sMessage Is Nothing Then
处理
End If
Catch ex As Exception
Finally
End Try
End While
Catch ex As System.Security.SecurityException
End Try
End Sub
推荐解决方案
Visual Basic code
Private Sub LoadListen()
Dim rd As New INIClass.clsReader(gPath & "\Config.Ini")
Dim port As Integer = rd.GetInteger("TCPIP", "ListenPort")
rd = Nothing
sckLis = New TcpListener(IPAddress.Any, port)
port = Nothing
StopLis = False
LisThread = New Threading.Thread(AddressOf StartListen)
LisThread.Name = "侦听进程"
LisThread.Start()
End Sub
Private Sub StartListen()
sckLis.Start()
Try
AddMsg("TCP/IP侦听器已启动.")
Do
Dim sckTmp As Socket = sckLis.AcceptSocket
Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(AddressOf Receive), sckTmp)
Next
If I >= Const_MaxClient Then sckTmp.Close()
sckTmp = Nothing
Loop Until StopLis = True
Catch e As Exception
If Not StopLis Then
AddMsg("[侦听线程出错]" & e.Message, KnownColor.Red)
RestartListen()
Else
CloseListen()
End If
End Try
End Sub
Public Function Receive(ByVal Sock As Socket) As Boolean
Dim ns As New NetworkStream(Sock)
Dim blnRtn As Boolean = False
Dim intRcv As Integer
Dim byteLen(1023) As Byte
Try
intRcv = ns.Read(byteLen, 0, byteLen.Length)
If intRcv = 0 Then
AddMsg("连接故障或通讯超时", KnownColor.Red)
Else
'对接收的Byte数组进行处理
blnRtn = True
End If
Catch e As Exception
AddMsg(e.Message, KnownColor.Red)
End Try
ns = Nothing
intRcv = Nothing
byteLen = Nothing
Return blnRtn
End Function
因为涉及单位的一些资料和python基础教程流程,我做了一些删除和修改处理,你参考一下吧。
其他解决方案
只要使用同步通讯方式,接受连接后如果没收到数据,阻塞是肯定会的,一直到超时时间到了才跳出来
关注 !
其他建议
没人理啊。。。
目前在While True 前向对方发一条空消息来处理,还有没有其他办法呢