服务端:
Dim address As IPAddress = IPAddress.Parse("192.168.1.5") serverSocket = New Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp) serverSocket.Bind(ipep) serverSocket.Listen(10) While True Try '在套接字上接收接入的连接 clientSocket = serverSocket.Accept() clientThread = New Thread(New ThreadStart(AddressOf ReceiveData)) clientThread.Start() Catch ex As Exception MessageBox.Show("listening Error: " & ex.Message) End Try End While Private Sub ReceiveData() Dim keepalive As Boolean = True Dim s As Socket = clientSocket Dim buffer As [Byte]() = New [Byte](1023) {} '根据收听到的客户端套接字向客户端发送信息 Dim clientep As IPEndPoint = DirectCast(s.RemoteEndPoint,IPEndPoint) lstServer.Items.Add("Client:" & Convert.ToString(clientep.Address) & "(" & clientep.Port & ")") Dim welcome As String = "Welcome to my test sever " Dim data As Byte() = New Byte(1023) {} data = Encoding.ASCII.GetBytes(welcome) s.Send(data,data.Length,SocketFlags.None) While keepalive '在套接字上接收客户端发送的信息 Dim bufLen As Integer = 0 Try bufLen = s.Available s.Receive(buffer,bufLen,SocketFlags.None) If bufLen = 0 Then Continue Try End If Catch ex As Exception MessageBox.Show("Receive Error:" & ex.Message) Return End Try clientep = DirectCast(s.RemoteEndPoint,IPEndPoint) Dim clientcommand As String = System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen) lstServer.Items.Add(clientcommand & "(" & Convert.ToString(clientep.Address) & ":" & clientep.Port & ")") End While End Sub
客户端:
'创建一个套接字 Dim ipep As New IPEndPoint(IPAddress.Parse("127.0.0.1"),6001) clientSocket = New Socket(AddressFamily.InterNetwork,ProtocolType.Tcp) '将套接字与远程服务器地址相连 Try clientSocket.Connect(ipep) Catch ex As SocketException MessageBox.Show("connect error: " + ex.Message) Return End Try While True '接收服务器信息 Dim bufLen As Integer = 0 Try bufLen = clientSocket.Available clientSocket.Receive(data,SocketFlags.None) If bufLen = 0 Then Continue Try End If Catch ex As Exception MessageBox.Show("Receive Error:" & ex.Message) Return End Try Dim clientcommand As String = System.Text.Encoding.ASCII.GetString(data).Substring(0,bufLen) lstClient.Items.Add(clientcommand) End While '向服务器发送信息 Dim data As Byte() = New Byte(1023) {} data = Encoding.ASCII.GetBytes(txtClient.Text) clientSocket.Send(data,SocketFlags.None)