本帖最后由 love5173 于 2011-5-6 20:52 编辑
如题,tcp如何同时监听多个连接,这些连接不定时的断开跟连接
这个是仿照帮助里的例子写的单连接的,即便是单连接,我断开再重新连的时候也不能再连了
#include <GUIConstantsEx.au3>
Opt('MustDeclareVars', 1)
Opt("GUIOnEventMode",1)
Example()
Func Example()
Local $szIPADDRESS = @IPAddress1
Local $nPORT = 33891
Local $MainSocket, $GOOEY, $edit, $ConnectedSocket, $szIP_Accepted
Local $msg, $recv
; 启动 TCP 服务
;==============================================
TCPStartup()
; 建立监听套接字 "SOCKET".
; 使用您的IP地址和端口 33891.
;==============================================
$MainSocket = TCPListen($szIPADDRESS, $nPORT)
; 如果套接字创建失败, 则退出.
If $MainSocket = -1 Then Exit
; 创建消息 GUI
;==============================================
$GOOEY = GUICreate("GM报警服务器(本机IP: " & $szIPADDRESS & ")", 360, 200)
$edit = GUICtrlCreateEdit("", 10, 10, 280, 180)
GUISetState()
GUISetOnEvent($GUI_EVENT_CLOSE, "gui")
$ConnectedSocket = -1
Do
$ConnectedSocket = TCPAccept($MainSocket)
Until $ConnectedSocket <> -1
$szIP_Accepted = SocketToIP($ConnectedSocket)
While 1
$recv = TCPRecv($ConnectedSocket, 2048)
;If @error Then ExitLoop
If $recv <> "" Then
GUICtrlSetData($edit, _
$szIP_Accepted & " > " & $recv & @CRLF & GUICtrlRead($edit))
For $i=0 To 2
_TalkOBJ($szIP_Accepted&"G M 报警 请及时处理")
Next
EndIf
ContinueLoop
WEnd
If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)
TCPShutdown()
EndFunc ;==>Example
; 函数将从一个连接套接字返回IP地址
;----------------------------------------------------------------------
Func SocketToIP($SHOCKET)
Local $sockaddr, $aRet
$sockaddr = DllStructCreate("short;ushort;uint;char[8]")
$aRet = DllCall("Ws2_32.dll", "int", "getpeername", "int", $SHOCKET, _
"ptr", DllStructGetPtr($sockaddr), "int*", DllStructGetSize($sockaddr))
If Not @error And $aRet[0] = 0 Then
$aRet = DllCall("Ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($sockaddr, 3))
If Not @error Then $aRet = $aRet[0]
Else
$aRet = 0
EndIf
$sockaddr = 0
Return $aRet
EndFunc ;==>SocketToIP
Func gui()
Switch @GUI_CtrlId
Case $GUI_EVENT_CLOSE
Exit
EndSwitch
EndFunc ;==>gui
Func _TalkOBJ($s_text)
Local $o_speech = ObjCreate("SAPI.SpVoice")
$o_speech.Speak($s_text)
$o_speech = ""
EndFunc
|