谁帮我用VB的winsock控件写个简单的服务器和客户端连接啊,复制的不要,要写简单点

2024-11-12 16:51:34
推荐回答(1个)
回答1:

首先 服务端 窗体设计放置text1和text2文本框 Command1和Command12按钮 winsock的名称改为sockserver

输入代码为:
Dim SendMsg As String

Private Sub Form_Load()
sockserver.LocalPort = 2000
sockserver.Listen
Text1.Locked = True
End Sub

Private Sub SockServer_ConnectionRequest(ByVal requestID As Long)
If sockserver.State <> sckClosed Then sockserver.Close
sockserver.Accept requestID
End Sub

Private Sub SockServer_DataArrival(ByVal bytesTotal As Long)
Dim s As String
sockserver.GetData s
If Text1.Text = "" Then
Text1.Text = s
Else
Text1.Text = Text1.Text & vbCrLf & s
End If
End Sub

Private Sub Command1_Click()
On Error GoTo err
SendMsg = Text2.Text
sockserver.SendData SendMsg
err:
If err.Number = 40006 Then
MsgBox "网络出错.", 48, "提示"
End If

End Sub

Private Sub sockserver_SendComplete()
If Text1.Text = "" Then
Text1.Text = SendMsg
Else
Text1.Text = Text1.Text & vbCrLf & SendMsg
End If
End Sub

Private Sub Command2_Click()
sockserver.Close
End
End Sub

Private Sub Form_Unload(Cancel As Integer)
sockserver.Close
End Sub

客户端窗体和服务端一样 只是winsock的名称改为 SockCL
代码如下:
Dim SendMsg As String

Private Sub Form_Load()
SockCL.RemoteHost = "127.0.0.1"
SockCL.RemotePort = 2000
SockCL.Connect
End Sub
Private Sub SockCl_DataArrival(ByVal bytesTotal As Long)
Dim DataStr As String
On Error GoTo err

SockCL.GetData DataStr
If Text1.Text = "" Then
Text1.Text = DataStr
Else
Text1.Text = Text1.Text & vbCrLf & DataStr
End If
err:
If err.Number = 40006 Then
MsgBox "网络错误.", 48, "提示"
End If

End Sub

Private Sub Command1_Click()
On Error GoTo err
If Text2.Text = "" Then
MsgBox "请输入发送信息,", 48, "提示"
Else
SendMsg = Text2.Text
SockCL.SendData SendMsg

End If
err:
If err.Number = 40006 Then
MsgBox "网络错误.", 48, "提示"
End If
End Sub

Private Sub SockCL_SendComplete()
If Text1.Text = "" Then
Text1.Text = endMsg
Else
Text1.Text = Text1.Text & vbCrLf & SendMsg
End If
End Sub

Private Sub Command2_Click()
SockCL.Close
End
End Sub

这是一个简单的客户端和服务器 通信的事例!先开启服务端然后再开启客户端!~