VB.net学习笔记之聊天工具Client端:System.Net.Sockets

新开一个博客,把以前学习的笔记整理整理,防止忘记

1.变量定义:

    Dim sender1 As New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp) '用来处理发送和接收消息的Socket实例
    Dim bytes(1024) As Byte
    Dim msg As Byte()           '发送的消息
    Dim bytesRec As Integer     '接收到的数据的长度
    Dim sbytes(1024) As Byte    '接收到的数据流
    Dim data As String = Nothing '处理后的接收到的消息
    Dim t As System.Threading.Thread

2.请求连接服务端:

    '启动请求连接
        Control.CheckForIllegalCrossThreadCalls = False
        t = New Thread(AddressOf waitdata)
        t.Start()
    '设置并连接服务端IP地址
    Public Sub waitdata()
        On Error GoTo wrong
        bool = InputBox("Please input the IP address")
        Dim handler As New System.Net.IPEndPoint(Net.IPAddress.Parse(bool), 9990)
        Me.Text = "Connect to the Server..."
        Dim localEndPoint As New System.Net.IPEndPoint(Net.IPAddress.Parse(bool), 9990)
        sender1.Connect(handler)
        Me.Text = "Connect to the server Successfully!"
        Button3.Text = "已连接"
        Dim p As System.Threading.Thread
        p = New Thread(AddressOf resdata)
        p.Start()
wrong:
    End Sub

3.接收消息并处理:

    Public Sub resdata()
        On Error GoTo wrong
        While (True)
            bytes = New Byte(1024) {}
            bytesRec = sender1.Receive(bytes) '接收数据 
            If bytesRec > 0 Then
                data = System.Text.Encoding.Unicode.GetString(bytes, 0, bytesRec) '字节消息流转码为 String
                RichTextBox1.AppendText(data)
            Else
                Continue While
            End If
        End While
        Exit Sub
wrong:
        sender1.Shutdown(Net.Sockets.SocketShutdown.Both)
        sender1.Close()
        MsgBox("连接断开!")
        Me.Text = "失去连接"
    End Sub
4.发送消息
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        On Error GoTo wrong
        msg = System.Text.Encoding.Unicode.GetBytes(RichTextBox2.Text)
        sender1.Send(msg)   '发送消息
        RichTextBox2.Text = ""
        Exit Sub
wrong:
        MsgBox("连接断开!")
    End Sub

Client端和Server端的区别并不是很大,主要有服务端首先开启监听端口并且轮询监听是否有连接进来,之后由客户端请求连接端口;服务端收到连接后,同意连接,连接成立,双方建立一个新的Socket来进行消息传输。



你可能感兴趣的:(VB.net)