TCP监听为何经常丢消息
;服务器!! 先运行我 !!!!!!!!!!!!!!!$g_IP = "10.32.88.123" ;10.18.126.40;10.18.254.54
; 开始 TCP 服务
;==============================================
TCPStartUp()
; 创建监听套接字(SOCKET)
;==============================================
$MainSocket = TCPListen($g_IP, 65432,100 )
If $MainSocket = -1 Then Exit
;查看客户端连接
;--------------------
While 1
$ConnectedSocket = TCPAccept( $MainSocket)
If $ConnectedSocket >= 0 Then
$recv = TCPRecv($ConnectedSocket, 2048)
msgbox(0,"Sever",$ConnectedSocket & "," & $recv)
EndIf
Wend
----------------------------------------
以上是服务端
以下是客户端
-------------------------------------
;CLIENT!!!!!!!! Start SERVER First... dummy!!
$g_IP = "10.32.88.123";10.32.65.78"
$g_localIp = @IPAddress1
;
; Start The TCP Services
;==============================================
TCPStartUp()
; Connect to a Listening "SOCKET"
;==============================================
$socket = TCPConnect( $g_IP, 65432 )
For $i=1 To 10
$num=TCPSend($socket, StringToBinary ("1234567" & @CRLF))
;Sleep(5000)
Next
If $socket = -1 Then
MsgBox(0,"1",@error)
;Exit
EndIf
TCPShutdown ( )
----------------------------------------------------------------------
逻辑就是客户端向服务端发送一个字符串“1234567”,服务端把收到的字符串打印出来
可是服务端有时候能正常打印,有时候就只能打印一个空字符串
泪奔啊,急求高手解答 自己先顶一下啊 自己先顶一下啊 不要用MSG之类阻断函数来显示获取到的信息。
输出到文本或建立GUI再输出吧! 试过写到文件中,也一样的 回复 5# solo_k
以前收藏的。
服务端:
Local $szIPADDRESS = @IPAddress1;你的公共IP地址
Local $nPORT = 33891;端口
Local $MainSocket, $GOOEY, $edit, $ConnectedSocket, $szIP_Accepted
Local $msg, $recv
TCPStartup()
$MainSocket = TCPListen($szIPADDRESS, $nPORT)
$GOOEY = GUICreate("My Server (IP: " & $szIPADDRESS & ")", 300, 200)
$edit = GUICtrlCreateEdit("", 10, 10, 280, 180)
GUISetState()
$ConnectedSocket = -1
Do
$ConnectedSocket = TCPAccept($MainSocket)
Until $ConnectedSocket <> -1
While 1
$msg = GUIGetMsg()
If $msg = $GUI_EVENT_CLOSE Then ExitLoop
$recv = TCPRecv($ConnectedSocket, 2048)
If @error Then ExitLoop
If $recv <> "" Then GUICtrlSetData($edit, $recv & @CRLF & GUICtrlRead($edit))
WEnd
If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)
TCPShutdown()客户端:Local $ConnectedSocket, $szData
Local $szIPADDRESS = @IPAddress1
Local $nPORT = 33891
TCPStartup()
$ConnectedSocket = -1
$ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)
If @error Then
MsgBox(4112, "错误", "TCP连接失败,服务端未启用!错误代码: " & @error)
Else
While 1
$szData = InputBox("发送数据给服务端", @LF & @LF & "输入一个要发送给服务端的数据:")
If @error Or $szData = "" Then ExitLoop
TCPSend($ConnectedSocket, $szData)
If @error Then ExitLoop
WEnd
EndIf
回复 6# user3000
亲,你这个就是帮助文档里的范例啊,还是会丢消息的,不信你用客户端发10次消息试试,总会有几次收到的消息是空
不过还是谢谢了 回复 7# solo_k
我以前用过没有这问题。
现在又在本机上测试了几下,不设延迟,服务端同样全收到了发过来的消息。
也许是你网络问题,丢包了? 回复 8# user3000
网络没问题,我搜了下,应该是TCP粘包引起的,可是不知道该怎么处理
页:
[1]