服务端持续运行! 同一机器可运行多个客户端, 并独立地与服务端进行通讯!
应该达到你的要求了!
服务端代码:
;;';SERVER:
$Form1 = GUICreate("服务端", 638, 521)
$edit = GUICtrlCreateEdit('', 8, 8, 625, 511)
Local $sSrvIP = @IPAddress1, $iPort = 65432
Global $MainSocket, $aConnected[1][2] = [[0]]
TCPStartUp()
$MainSocket = TCPListen($sSrvIP, $iPort, $iPort)
If $MainSocket = -1 Then Exit
GUICtrlSetData($edit, "状态正常!", 1)
GUISetState(@SW_SHOW)
While 1
Sleep(100)
Accept()
Recv()
WEnd
;TCPShutdown()
Func Accept()
Local $ConnectedSocket, $sEdit
$ConnectedSocket = TCPAccept($MainSocket)
If $ConnectedSocket <> -1 Then
$aConnected[0][0] += 1
ReDim $aConnected[$aConnected[0][0] + 1][2]
$aConnected[$aConnected[0][0]][0] = $ConnectedSocket
$aConnected[$aConnected[0][0]][1] = SocketToIP($ConnectedSocket)
EndIf
Return
EndFunc
Func Recv()
Local $sRecv, $sEdit, $i = 1,$hQuery,$aRow,$cids
While $i <= UBound($aConnected) - 1
$sRecv = TCPRecv($aConnected[$i][0], 2048, 1);
If $sRecv <> "" Then
$sRecv = BinaryToString($sRecv, 4)
GUICtrlSetData($edit, 'From ' & $aConnected[$i][1] & ': ' & $sRecv & @CRLF, 1)
TCPSend($aConnected[$i][0],$sRecv & " from server")
EndIf
$i += 1
WEnd
Return
EndFunc
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
Return $aRet
EndFunc ;==>SocketToIP
客户端代码:
Local $sSrvIP = @IPAddress1, $iPort = 65432, $Socket
$Form1 = GUICreate('Client', 516, 316)
$edit = GUICtrlCreateEdit('', 8, 8, 500, 200)
$but = GUICtrlCreateButton('发送', 150, 230, 75, 28)
GUISetState(@SW_SHOW)
TCPStartup()
$Socket = TCPConnect($sSrvIP, $iPort) ; 创建一个套接字连接到已经存在的服务器
If $Socket = -1 Then
MsgBox(0, "提示", "服务端未开启! ")
_Exit()
EndIf
While 1
Switch GUIGetMsg()
Case -3
_exit()
Case $but
_send()
EndSwitch
WEnd
Func _Exit()
TCPCloseSocket($Socket)
Exit
EndFunc ;==>_Exit
Func _send()
$sMsg = GUICtrlRead($edit)
If $sMsg = "" Then Return MsgBox(16, 'Err', '请先输入数据! ', '', $Form1)
TCPSend($Socket, StringToBinary($sMsg)) ; 发送信息
While 1
$recv = TCPRecv($Socket, 2048)
If $recv <> "" Then
$recv = BinaryToString($recv)
MsgBox(0, "receive", $recv)
ExitLoop
EndIf
WEnd
Return
EndFunc ;==>_send
|