另起一個(gè)線程,在里面循環(huán)receive,每收到一個(gè)數(shù)據(jù)就進(jìn)行分析,特殊命令如exit,執(zhí)行udpclient.close(),其他數(shù)據(jù)委托到主線程。
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),營山企業(yè)網(wǎng)站建設(shè),營山品牌網(wǎng)站建設(shè),網(wǎng)站定制,營山網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,營山網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
給你個(gè)udp多播例子,廣播不是很清楚,呵呵
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Inherits System.Windows.Forms.Form
Dim port As String
Dim ipadd As String
Dim ipend As IPEndPoint
Dim sendudp As New UdpClient()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Dim ipadress As IPAddress
ipadress = IPAddress.Parse(TextBox1.Text)
'sendport = Int32.Parse(TextBox2.Text)
'ipend = New IPEndPoint(ipadress, sendport)
Try
sendudp.JoinMulticastGroup(ipadress)
MessageBox.Show("啟動(dòng)完成!")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
網(wǎng)上很多相關(guān)的現(xiàn)成的代碼
你需要知道的一點(diǎn)是數(shù)據(jù)接收不是接收一次就完了 接收端根本不知道數(shù)據(jù)什么時(shí)候要過來 所以數(shù)據(jù)端應(yīng)該一直重復(fù)著"等待-接收"的過程 于是就有了要在線程中接收數(shù)據(jù)的代碼
'xiansr.2014/2/7 vb.net2010 調(diào)試通過
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim udpClient As New UdpClient(11000)
Try
udpClient.Connect("127.0.0.1", 11000)
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(RichTextBox1.Text)
udpClient.Send(sendBytes, sendBytes.Length)
Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
Dim receiveBytes As [Byte]() = udpClient.Receive(RemoteIpEndPoint)
Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
RichTextBox2.Text = "接收到: " + returnData.ToString()
'Debug.Print(("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString()))
udpClient.Close()
Catch ex As Exception
stop
End Try
End Sub
End Class
服務(wù)器先進(jìn)行
Bind ()綁定服務(wù)器的端口
然后BeginReceive接受客戶端發(fā)送的數(shù)據(jù)
客戶端Bind ()綁定客戶端接受和發(fā)送數(shù)據(jù)的端口
SendTo()來發(fā)送數(shù)據(jù)就可以
不需要進(jìn)行BeginConnect,因?yàn)閁DP不需要連接
DatagramSocket用于接收和發(fā)送UDP的Socket實(shí)例。該類有3個(gè)構(gòu)造函數(shù):DatagramSocket():通常用于客戶端編程,它并沒有特定監(jiān)聽的端口,僅僅使用一個(gè)臨時(shí)的。程序會(huì)讓操作系統(tǒng)分配一個(gè)可用的端口。DatagramSocket(int port):創(chuàng)建實(shí)例,并固定監(jiān)聽Port端口的報(bào)文。通常用于服務(wù)端。