关键词搜索

源码搜索 ×
×

vb.netSocket多客户端连接初试

发布2021-02-10浏览590次

详情内容

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

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

    在这里插入图片描述

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载