说明
之前用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