VB.net学习笔记之聊天工具Server端: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.打开并监听端口:

    '启动监听
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Control.CheckForIllegalCrossThreadCalls = False
        Me.Text = "Connect to the Client..."
        Button1.Text = "监听中..."
        Dim t As System.Threading.Thread = New Thread(AddressOf waitdata)
        t.Start()
    End Sub
    '监听并等待消息
    Public Sub waitdata()
        Dim listener As New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp) '用来处理监听端口的Socket实例
        Dim localEndPoint As New System.Net.IPEndPoint(Net.IPAddress.Parse("0.0.0.0"), 9990)
        listener.Bind(localEndPoint)
        listener.Listen(10)
        handler = listener.Accept()
        Button1.Text = "已连接"
        Me.Text = "Connect to the Client successfully!"
        Dim p As System.Threading.Thread = New Thread(AddressOf resdata)   '不断进行轮询检测是否有消息进来
        p.Start()
    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



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