VB.net Socket Udp收发数据包示例源码
Posted 津津有味0202
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VB.net Socket Udp收发数据包示例源码相关的知识,希望对你有一定的参考价值。
Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports System.Threading
Public Class Form1
Dim PortNumber As Integer = 39192 侦听端口号
Dim ListenerSock As Socket 侦听socket
Dim ListenerThre As Thread 侦听线程
Dim LocalIp As String 本地ip64
Dim ready As Boolean = False 线程运行标识
Dim machinnos As String
Delegate Sub Gxdjs(ByVal data As String) 线程内更新UI传送一个显示参数
Delegate Sub EditUi(ByVal data0 As String, ByVal data1 As String) 线程内更新UI传送两个参数
Private Sub Form1_Disposed(sender As Object, e As EventArgs) Handles Me.Disposed
ListenerSock.Close()
ready = False
ListenerThre.Abort()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
getIp()
StartListener() 开始侦听
End Sub
Private Sub StartListener()
Dim LocalPoint As IPEndPoint
While Not ready 向用户询问侦听端口号。用户可以直接回车,表示选择默认的。
Try
LocalPoint = New IPEndPoint(IPAddress.Parse(LocalIp), PortNumber)
ListenerSock = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
ListenerSock.Bind(LocalPoint)
ListenerThre = New Thread(AddressOf ThrListener)
ListenerThre.Start()
ready = True
Catch ex As Exception
ListenerSock.Close()
ready = False
ListBox1.Items.Add("ERROR:" & vbCrLf & ex.Message & vbCrLf)
End Try
End While
End Sub
Public Sub getIp() 获取本机所有网卡的IP
Dim Address() As System.Net.IPAddress
Dim i As Integer
Address = Dns.GetHostByName(Dns.GetHostName()).AddressList
If UBound(Address) < 0 Then
MsgBox("未能查找到本台电脑安装的网卡,暂不能启动本软件。", MsgBoxStyle.Critical + vbOKOnly, "注意")
End
Else
For i = 0 To UBound(Address)
ComboBox1.Items.Add(Address(i).ToString())
Next
ComboBox1.SelectedIndex = 0
LocalIp = ComboBox1.Text.Trim()
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
ListenerSock.Close()
ready = False
ListenerThre.Abort()
LocalIp = ComboBox1.Text.Trim()
StartListener() 开始侦听已选网卡的UDP端口
Catch
End Try
End Sub
Private Sub ThrListener() 侦听线程
While ready
Try
Dim bytes(1024) As Byte
Dim dataArray() As String
Dim RemotePoint As System.Net.EndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
Dim NumGet As Integer
Dim Msg As String
Dim Sendinf As String
Dim SendBuf As Byte()
Dim DevBufferIpAddrStr As String
Dim DevBufferRemoteAddrStr As String
Dim DevBufferUseTimeStr As String
Dim DevRecFramesStr As String
Dim DevBufferMachinStr As String
Dim DevBufferCardidStr As String
Dim DevBufferUseMoneryStr As String
Dim DevBufferSerialNumStr As String
Dim ipep As IPEndPoint
NumGet = ListenerSock.ReceiveFrom(UDP 协议 C# UdpClient乱序接收数据包丢失的问题 Socket ReceiveBufferSize