VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > VB.net教程 >
  • 使用vb.net开发简单的socket通信

使用vb.net开发简单的socket通信(环境是visual stdio 2019)

    • 说明
      • 参考文章
    • 实现功能
  • 效果展示
  • 代码
    • 服务端
    • 客户端
  • 总结

 

说明

之前用vb6编程时都是用的winsock控件进行网络通信,现在研究.net平台发现网上说的socket更好用,不过在网上一直都没有找到合适的代码,下面我来详细讲解下我的方法(小白一枚,望大佬指出不足!!!)

参考文章

C#实现socket通信:https://www.cnblogs.com/liangweitao/p/10862611.html
vb.net检测端口是否被占用 https://blog.csdn.net/u011993802/article/details/106954226

实现功能

一个服务端和多个客户端的互动

效果展示

在这里插入图片描述

代码

服务端

Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation
Imports System.Text
Imports System.Threading
Public Class Form1
    Private mynewTextBox As New TextBox         ''''''''''''''''''''''''''''''添加需要的控件
    Private sendTextBox As New TextBox
    Private portTextBox As New TextBox
    Private newButton As New Button
    Private sendButton As New Button

    Private ip As IPAddress = IPAddress.Any  '''''''''''''''''''''''''''''''''''''''''''添加需要的元素
    Private newPort As Integer = 10000
    Private point(1000) As IPEndPoint
    Private socketSend(1000) As Socket
    Private nx As Integer = -1   '''''''''''''''''''''''''标记连接了几个客户端
    Private Sub ShowMsg(ByVal msg As String) ''''''''''''''''''''用于展示信息
        mynewTextBox.AppendText(msg & vbCrLf)
    End Sub
    Private Function searchindexbyport(ByVal arr As Array, ByVal theport As Integer) As Integer ''''''''''''''''''''''''''''''''根据端口查找用于发送信息的socket(socketSend)的指数
        Try
            Dim mypoint As IPEndPoint
            mypoint = New IPEndPoint(ip, Convert.ToInt32(theport))
            searchindexbyport = -1
            For i As Integer = 0 To arr.Length
                If arr(i).ToString = mypoint.ToString Then
                    searchindexbyport = i
                    Exit For
                End If
            Next
        Catch
        End Try
    End Function
    Private Sub Send() '''''''''''''''''''''''''''发送消息
        Dim str As String
        Dim socketSendnum As Integer
        str = sendTextBox.Text.Trim()
        socketSendnum = searchindexbyport(point, Val(portTextBox.Text))
        Dim buffer As Byte() = Encoding.UTF8.GetBytes(str)
        socketSend(socketSendnum).Send(buffer)
    End Sub

    Private Sub openS()            ''''''''''''''''''''''打开客户端,建立连接
        Try
            Dim Sname As String = "C:\Users\dell\Desktop\工程\使用vb.net开发简单的socket通信\客户端\bin\Debug\客户端.exe"     ''''''''''''''''这里写自己客户端的文件位置

            Dim socketWatch As Socket
            Dim thread As Thread

            nx = nx + 1
            getnewPort()
            socketWatch = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            point(nx) = New IPEndPoint(ip, Convert.ToInt32(newPort))
            socketWatch.Bind(point(nx))
            ShowMsg(String.Join(" ", "监听成功! ", newPort))
            socketWatch.Listen(10)
            thread = New Thread(AddressOf Listen) ''''''''''''''''''''''添加线程以实现侦听过程
            thread.Name = "thread" & nx.ToString '''''''''''''''''''''方便后期调试
            thread.IsBackground = True
            thread.Start(socketWatch)

            Sname = String.Join(" ", Sname, newPort)'''''''''''''''''''''''''shell客户端同时传递端口参数
            Shell(Sname, AppWinStyle.NormalFocus)

        Catch
        End Try
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ''''''''''''''''''''''''''''load事件初始化控件

        mynewTextBox.Multiline = True
        mynewTextBox.Height = 200
        mynewTextBox.Width = 250
        mynewTextBox.Location = New Point(0, 0)
        Me.Controls.Add(mynewTextBox)

        sendTextBox.Width = 200
        sendTextBox.Location = New Point(250, 0)
        sendTextBox.Text = ”在这个文本框输入你要发送的消息“
        Me.Controls.Add(sendTextBox)

        portTextBox.Width = 200
        portTextBox.Location = New Point(250, 70)
        portTextBox.Text = ”10001“
        Me.Controls.Add(portTextBox)

        sendButton.Location = New Point(20, 220)
        sendButton.Text = "发送"
        Me.Controls.Add(sendButton)
        AddHandler sendButton.Click, AddressOf Send  '''''''''''''''''''''绑定事件

        newButton.Location = New Point(100, 220)
        newButton.Text = "新增客户端"
        Me.Controls.Add(newButton)
        AddHandler newButton.Click, AddressOf openS

        Control.CheckForIllegalCrossThreadCalls = False       '''''''''''''''''''''''确保可以安全的访问窗体控件


    End Sub


    Private Sub getnewPort() '''''''''''得到一个未使用端口,并保存到newport里面
        Do
            If PortInUse(newPort) <> 0 Then newPort = newPort + 1
        Loop Until PortInUse(newPort) = 0
    End Sub
    Public Shared Function PortInUse(ByVal port As Integer) As Boolean '''''''''''''''''''判断一个端口是否被占用
        Try
            '查看UDP端口是否被占用
            Dim ipProperties As IPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties()
            Dim ipEndUdpPoints() As IPEndPoint = ipProperties.GetActiveUdpListeners
            For Each endPoint As IPEndPoint In ipEndUdpPoints
                If endPoint.Port = port Then
                    Return True
                End If
            Next endPoint

            '查看TCP端口是否被占用
            Dim ipEndTcpPoints() As IPEndPoint = ipProperties.GetActiveTcpListeners
            For Each endPoint As IPEndPoint In ipEndTcpPoints
                If endPoint.Port = port Then
                    Return True
                End If
            Next endPoint
            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Sub Listen(ByVal o As Object) ''''''''''''''''''侦听
        Try
            Dim socketWatch As Socket
            socketWatch = TryCast(o, Socket)

            While True
                socketSend(nx) = socketWatch.Accept()
                ShowMsg(socketSend(nx).RemoteEndPoint.ToString() & ":" & "连接成功!")
                Dim r_thread As Thread = New Thread(AddressOf Received)
                r_thread.IsBackground = True
                r_thread.Start(socketSend(nx))

            End While

        Catch
        End Try
    End Sub

    Private Sub Received(ByVal o As Object) '''''''''''''''接收客户端传来的消息
        Try
            Dim socketSend As Socket = TryCast(o, Socket)

            While True
                Dim buffer As Byte() = New Byte(3145727) {}
                Dim len As Integer = socketSend.Receive(buffer)

                If len = 0 Then
                    Exit While
                End If

                Dim str As String = Encoding.UTF8.GetString(buffer, 0, len)
                ShowMsg(socketSend.RemoteEndPoint.ToString & ":" & str) '''''''''''''''''''''''''''将消息进行展示
            End While

        Catch
        End Try
    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
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174

客户端

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

Public Class Form1
    ''''''''''''''''''''''''''''''添加需要的控件
    Private mynewTextBox As New TextBox
    Private sendTextBox As New TextBox
    Private sendButton As New Button
    '''''''''''''''''''''''''''''''''''''''添加需要的元素
    Private myIP As String = "192.168.0.104"         '''''''''''''''''''''''''''''''写入自己的IP
    Private myPort As Integer
    Private socketSend As Socket
    Private Sub ShowMsg(ByVal str As String) ''''''''''''''''''''用于展示信息
        mynewTextBox.AppendText(str & vbCrLf)
    End Sub
    Private Sub send() '''''''''''''''''''''''发送消息
        Try
            Dim msg As String = sendTextBox.Text.Trim()
            Dim buffer As Byte() = New Byte(3145727) {}
            buffer = Encoding.UTF8.GetBytes(msg)
            socketSend.Send(buffer)
        Catch
        End Try
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load     ''''''''''''''''''''''''''''load事件初始化控件
        myPort = Val(Command) ''''''''''''''''''''''''''得到服务端分配的端口

        mynewTextBox.Multiline = True
        mynewTextBox.Height = 200
        mynewTextBox.Width = 250
        mynewTextBox.Location = New Point(0, 0)
        Me.Controls.Add(mynewTextBox)

        sendTextBox.Width = 200
        sendTextBox.Location = New Point(250, 0)
        sendTextBox.Text = ”在这个文本框输入你要发送的消息“
        Me.Controls.Add(sendTextBox)

        sendButton.Location = New Point(20, 220)
        sendButton.Text = "发送"
        Me.Controls.Add(sendButton)
        AddHandler sendButton.Click, AddressOf send  '''''''''''''''''''''绑定事件


        Control.CheckForIllegalCrossThreadCalls = False
        ConnectS()
    End Sub

    Private Sub ConnectS() '''''''''''''''''''''''连接
        Try
            socketSend = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

            Dim ip As IPAddress = IPAddress.Parse(myIP)
            Dim point As IPEndPoint = New IPEndPoint(ip, Convert.ToInt32(myPort))
            socketSend.Connect(point)
            ShowMsg("连接成功!")
            Dim c_thread As Thread = New Thread(AddressOf Received)
            c_thread.IsBackground = True
            c_thread.Start()
        Catch __unusedException1__ As Exception
            ShowMsg("IP或者端口号错误...")
        End Try
    End Sub



    Private Sub Received() '''''''''''''''接收服务端传来的消息
        While True

            Try
                Dim buffer As Byte() = New Byte(3145727) {}
                Dim len As Integer = socketSend.Receive(buffer)

                If len = 0 Then
                    Exit While
                End If

                Dim str As String = Encoding.UTF8.GetString(buffer, 0, len)
                ShowMsg(socketSend.RemoteEndPoint.ToString & ":" & str)
            Catch
            End Try
        End While
    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

总结

以上就是我本次分享的代码,复制粘贴到新建的windows窗体应用的form1里面就可以运行试试!!!!第一次写这种文章,不是很会,希望可以帮到你!!有什么不懂的地方可以留言嘿嘿嘿


相关教程