Socket 客户端与服务端对话工具
:
Private Sub RunServer() Dim ConClient As Socket Dim strClientName As String = "" Dim bCExist As Boolean '客户端是否已经在列表中 Dim ClientIpEP As IPEndPoint Dim CNetWorkStream As NetworkStream Dim Reader As BinaryReader Do bCExist = False ConClient = CTcpListener.AcceptSocket '接收客户端的连接,返回一个socket SentButton.Enabled = True Try ClientIpEP = CType(ConClient.RemoteEndPoint, IPEndPoint) '获取socket的ipendpoint strClientName = Dns.GetHostEntry(ClientIpEP.Address).HostName '获取客户端的名称 Catch ex As SocketException ClientIpEP = Nothing MessageBox.Show(ex.Message) Continue Do End Try '检测该客户端是否已在列表中 Dim strName As String = "" For Each strName In ClientListBox.Items If String.Compare(strClientName, strName) = 0 Then bCExist = True 'Exit For '存在则退出查找 End If Next ' 客户列表中添加客户 If bCExist = False Then ClientListBox.Items.Add(strClientName) HistoryRichText.SelectionColor = Color.Green HistoryRichText.AppendText(strClientName & " 加入会话" & vbCrLf) HistoryRichText.ScrollToCaret() Continue Do End If Try CNetWorkStream = New NetworkStream(ConClient) Reader = New BinaryReader(CNetWorkStream) HistoryRichText.SelectionColor = Color.Blue HistoryRichText.AppendText(strClientName & "说" & vbCrLf) HistoryRichText.SelectionColor = Color.Black HistoryRichText.AppendText(Reader.ReadString() & vbCrLf) HistoryRichText.ScrollToCaret() Catch ex As Exception MsgBox(ex.Message) Finally ClientIpEP = Nothing CNetWorkStream = Nothing Reader = Nothing End Try ConClient.Disconnect(True) ' 关闭套接字 Loop System.Environment.Exit(System.Environment.ExitCode) End Sub
暂无评论