VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > VB.net教程 >
  • vb.netSocket多客户端连接初试

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Collections.Generic

Public Class Form1
    '声明一个线程,用于和客户机通讯
    Dim LinkThread As Thread
    '声明一个Socket用于侦听
    Dim ListenSocket As Socket


    Dim data As String = String.Empty

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Button1.Text = "开始侦听" Then       '判断是否正在侦听
            '获取要侦听的IP地址和端口
            Dim localEndPoint As New IPEndPoint(Net.IPAddress.Parse(TextBox1.Text), TextBox2.Text)
            '初始化Socket为IP4的版本 TCP协议
            ListenSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            '更改侦听按钮的显示
            Button1.Text = "停止侦听"
            Button1.BackColor = Color.Green
            '绑定端口
            ListenSocket.Bind(localEndPoint)
            '开始监听
            ShowMsg("开始侦听端口! ") '显示文本信息
            '最多连接100个客户端
            ListenSocket.Listen(100)
            '创建一个线程并且启动线程开始侦听端口
            LinkThread = New Thread(AddressOf listen)
            '设置为后台进程
            LinkThread.IsBackground = True
            '给线程传输一个参数,类型为Socket
            LinkThread.Start(ListenSocket)
        Else
            '更改侦听按钮的显示
            Button1.Text = "开始侦听"
            Button1.BackColor = SystemColors.Control
            Try
                '关闭Socket,并且结束线程(必须先关Socket再结束线程,否则出错)
                ListenSocket.Dispose()
                ListenSocket.Close()
                LinkThread.Abort()
            Catch
            End Try
            ShowMsg("停止侦听端口!")
        End If
    End Sub
    Private Sub listen(ByVal s As Socket)
        Dim SocketLis As Socket
        While True
            Try
                'SocketLis = s
                '新建一个Socket,并且等待客户端连接
                SocketLis = s.Accept() '等待接收客户端的连接
                Dic.Add(SocketLis.RemoteEndPoint.ToString, SocketLis) '把连接到的客户端IP和端口存到键值里
                ComboBox1.Items.Add(SocketLis.RemoteEndPoint.ToString) '把连接到的客户端IP和端口存到下拉框里
                '显示连接的客户端IP和端口
                ShowMsg("客户机已连接!" + SocketLis.RemoteEndPoint.ToString)
                '创建一个线程用于接收客户端数据
                LinkThread = New Thread(AddressOf ReciveData)
                LinkThread.IsBackground = True
                LinkThread.Start(SocketLis)
            Catch
            End Try
        End While

    End Sub
    Private Sub SocketSend()

        Dim Str As String = TextBox3.Text '去除文本框里的数据
        Dim msg As Byte() = Encoding.UTF8.GetBytes(Str) '把字符串转成字节
        Try
            Dim SelectNum As String = ComboBox1.SelectedItem.ToString '获取选定的客户端IP地址和端口
            Dic(SelectNum).Send(msg)
        Catch
            ShowMsg("请选择客户端!")
        End Try
    End Sub
    Dim SocketRec As Socket
    Private Sub ReciveData(ByVal s As Socket)
        While True

            SocketRec = s
                Dim bytes(1024) As Byte
                Dim bytesRec As Integer = SocketRec.Receive(bytes)
                data = Encoding.UTF8.GetString(bytes, 0, bytesRec)
            If data.Length > 0 Then
                '显示客户端发来的消息
                ShowMsg(SocketRec.RemoteEndPoint.ToString + ":" + data)
            Else
                Try
                    '如果接收到的数据包长度为0,则认为客户端已断开连接
                    ComboBox1.Items.RemoveAt(ComboBox1.FindString(SocketRec.RemoteEndPoint.ToString))     '把已经断开的客户端从列表里删除
                    Dic.Remove(SocketRec.RemoteEndPoint.ToString) '把已经断开的客户端从列表里删除
                    ShowMsg("客户端已断开!")

                    '以下代码,打印出DIC的所有项
                    'Dim list As New List(Of String)(Dic.Keys)
                    'Dim str As String
                    'For Each Str In list
                    '    ' Print string and also Item(string), which is the value.
                    '    ShowMsg(str)
                    'Next

                    '关闭接收数据的线程
                    SocketRec.Dispose()
                    SocketRec.Close()

                Catch

                End Try

            '显示连接的客户端IP和端口
            '返回侦听线程,继续侦听
            Exit Sub

                End If

        End While
    End Sub
    Dim Dic As Dictionary(Of String, Socket) = New Dictionary(Of String, Socket)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '禁用线程检测
        Control.CheckForIllegalCrossThreadCalls = False
    End Sub

    '在Listboxs里显示信息
    Private Sub ShowMsg(s As String)
        ListBox1.Items.Add(s)
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        SocketSend()
    End Sub


End Class

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143

客户端连接以后会显示客户端的IP和端口号并且在combotext1里增加客户端,客户端断开则会删除客户端
 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zp820625323123456/article/details/86602899

相关教程