udp协议,中文名为用户数据报协议,可以实现无需连接的数据传输,优点是速度快,缺点是数据不做检验,不可靠。很多即时通讯软件中会用到这种方式,本文中实现单客户端的udp通讯。
udp通讯无需建立连接,只需要知道远程设备的IP和端口即可,因此程序相对tcp简单多了。
假设两台设备(PC),client A和client B。udp传输不需要分客户端和服务端,程序是完全一样的。
程序:
udp也需要实例化socket,并且需要绑定本地端口。
bind
s = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Dim ipe As New IPEndPoint(IPAddress.Any, 11000)
s.Bind(ipe)
发送
Dim ipe As New IPEndPoint(IPAddress.Parse("192.168.1.109"), 11000)
Dim sendbyt(1024) As Byte
sendbyt = Encoding.GetEncoding("gb2312").GetBytes(TextBox1.Text)
s.SendTo(sendbyt, 0, sendbyt.Length, 0, ipe)
ListView1.Items.Add("me:" + TextBox1.Text + vbCrLf, 0)
TextBox1.Clear()
接收
While True
Dim recbyt(1024) As Byte
s.Receive(recbyt)
data1 = Encoding.GetEncoding("gb2312").GetString(recbyt)
Dim recdt1 As New recdtscok(AddressOf recdttt)
Me.Invoke(recdt1, data1)
End While
本示例程序中,我加了一些线程调用,使用了简单的托管,然后就是聊天窗口加了一些优化,比如使用listview做文本显示,加了图片区别和背景色。
完整程序:(client B)
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Form1
Dim s As Socket
Delegate Sub recdtscok(dt As String)
Dim data1 As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With ListView1
.FullRowSelect = True
.View = View.List
End With
s = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Dim ipe As New IPEndPoint(IPAddress.Any, 11000)
s.Bind(ipe)
Console.WriteLine("bind local port:" & ipe.Port.ToString())
Dim recth As New Thread(AddressOf recdt)
recth.Start()
End Sub
Private Sub recdt()
While True
Dim recbyt(1024) As Byte
s.Receive(recbyt)
data1 = Encoding.GetEncoding("gb2312").GetString(recbyt)
Dim recdt1 As New recdtscok(AddressOf recdttt)
Me.Invoke(recdt1, data1)
End While
End Sub
Private Sub recdttt(dt As String)
ListView1.Items.Add("client A:" + dt + vbCrLf, 1)
ListView1.Items(ListView1.Items.Count - 1).SubItems(0).BackColor = Color.Lime
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ipe As New IPEndPoint(IPAddress.Parse("192.168.1.109"), 11000)
Dim sendbyt(1024) As Byte
sendbyt = Encoding.GetEncoding("gb2312").GetBytes(TextBox1.Text)
s.SendTo(sendbyt, 0, sendbyt.Length, 0, ipe)
ListView1.Items.Add("me:" + TextBox1.Text + vbCrLf, 0)
TextBox1.Clear()
End Sub
End Class
这个完整程序是 client B设备的,client A和client B的程序完全一样,只是在发送的远程IPENDPOINT的参数改一下IP地址就行了。