vb.net中用UdpClient接收和发送的问题,求解?

lss652019 2010-12-17 05:15:20
' 向服务器发送数据(发送代码)
Public Function MDISendData(ByVal IP As String, ByVal Sport As Integer, ByVal Rport As Integer, ByVal Sdata As String) As Boolean
Dim locaipendpoint As New IPEndPoint(IPAddress.Parse(IP), Rport)
Try
If Not Udp1 Is Nothing Then
Udp1 = Nothing
End If
Udp1 = New UdpClient(Rport)
Udp1.Connect(locaipendpoint)
Dim sendbytes As Byte() = Encoding.UTF8.GetBytes(Sdata)
Udp1.Send(sendbytes, sendbytes.Length)
If Not Udp1 Is Nothing Then
Udp1.Close()
Udp1 = Nothing
End If
Catch ex As Exception
Throw ex
Return False
End Try
Return True
End Function

以上为发送,各位高手,请问如何写接收数据的代码,要用到套接字,求解?
...全文
162 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lss652019 2010-12-22
  • 打赏
  • 举报
回复
Imports System.IO
Imports System.Text
Imports System.Threading
Imports System.Net.Sockets
Imports System.Net

Public Class Form1 '定义网络套接字
Public Udp3 As UdpClient = Nothing
Public bytesdata As String
Public thread2 As Thread
Dim myUdpClient As UdpClient
Dim Server_IP2 As String = "127.0.0.1"
Dim RePort2 As String = 5000
Dim SendPort2 As String = 5001


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load '接收数据Server
thread2 = New Thread(New ThreadStart(AddressOf ThreadModel2))
thread2.Start()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click '发送数据Client
myUdpClient = New UdpClient()
Dim remoteIP As IPAddress = IPAddress.Parse(Server_IP2)
Dim iep As IPEndPoint = New IPEndPoint(remoteIP, RePort2)
Dim sendBytes As Byte() = Encoding.UTF8.GetBytes(Me.TextBox1.Text)
Try
myUdpClient.Send(sendBytes, sendBytes.Length, iep)
Catch ex As Exception
MsgBox(ex.ToString())
End Try

If Not Udp3 Is Nothing Then
myUdpClient.Close()
End If
End Sub
Public Sub ThreadModel2()

Try
Dim groupEP As New IPEndPoint(IPAddress.Parse(Server_IP2), RePort2)
Udp3 = New UdpClient()
Udp3.Connect(groupEP)

While True
Try
bytesdata = Encoding.UTF8.GetString(Udp3.Receive(groupEP))
Me.TextBox1.Text = bytesdata
Catch ex As Exception
Throw ex
End Try
End While
Catch ex As Exception
MsgBox(ex.ToString())
End Try
If Not Udp3 Is Nothing Then
Udp3.Close()
End If
End Sub

Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If Not Udp3 Is Nothing Then
Udp3.Close()
End If
If thread2.IsAlive() Then
thread2.Abort()
End If
End Sub
End Class

以上代码不对,接收不到数据,没反应,请问么改,你也可以复制到你的电脑上测试
wood87654321 2010-12-20
  • 打赏
  • 举报
回复
Udp.Receive对应Udp.Send,由于其为阻塞方法,要连续接收应将这句放在一个循环中
QQRN 2010-12-20
  • 打赏
  • 举报
回复
你在局域网用么?UDP很不稳定的.

16,554

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧