读书人

求异步UDP范例

发布时间: 2012-08-07 14:54:48 作者: rapoo

求异步UDP实例
要效率高点的,从未做过多线程的东西,请大家尽量详细些


[解决办法]
参考:http://social.microsoft.com/Forums/zh-CN/vbasiczhchs/thread/646ae1aa-e105-44e6-ba98-3b7595779c75
[解决办法]
看看:http://download.csdn.net/source/1046138

[解决办法]
参考
参考
[解决办法]

C# code
using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;using System.Threading;namespace AsyncServer{    public class UdpState    {        public UdpClient udpClient;        public IPEndPoint ipEndPoint;        public const int BufferSize = 1024;        public byte[] buffer = new byte[BufferSize];        public int counter = 0;    }    public class AsyncUdpSever    {        private IPEndPoint ipEndPoint = null;        private IPEndPoint remoteEP = null;        private UdpClient udpReceive = null;        private UdpClient udpSend = null;        private const int listenPort = 1100;        private const int remotePort = 1101;        UdpState udpReceiveState = null;        UdpState udpSendState = null;        private ManualResetEvent sendDone = new ManualResetEvent(false);        private ManualResetEvent receiveDone = new ManualResetEvent(false);        public AsyncUdpSever()        {            ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort);            remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);            udpReceive = new UdpClient(ipEndPoint);            udpSend = new UdpClient();            udpReceiveState = new UdpState();                        udpReceiveState.udpClient = udpReceive;            udpReceiveState.ipEndPoint = ipEndPoint;            udpSendState = new UdpState();            udpSendState.udpClient = udpSend;            udpSendState.ipEndPoint = remoteEP;        }        public void ReceiveMsg()        {            Console.WriteLine("listening for messages");            while(true)            {                lock (this)                {                       IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);                    receiveDone.WaitOne();                    Thread.Sleep(100);                }            }        }        private void ReceiveCallback(IAsyncResult iar)        {            UdpState udpReceiveState = iar.AsyncState as UdpState;            if (iar.IsCompleted)            {                Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);                string receiveString = Encoding.ASCII.GetString(receiveBytes);                Console.WriteLine("Received: {0}", receiveString);                //Thread.Sleep(100);                receiveDone.Set();                SendMsg();            }        }        private void SendMsg()        {            udpSend.Connect(udpSendState.ipEndPoint);            udpSendState.udpClient = udpSend;            udpSendState.counter ++;            string message = string.Format("第{0}个UDP请求处理完成!",udpSendState.counter);            Byte[] sendBytes = Encoding.Unicode.GetBytes(message);            udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);            sendDone.WaitOne();        }        private void SendCallback(IAsyncResult iar)        {            UdpState udpState = iar.AsyncState as UdpState;            Console.WriteLine("第{0}个请求处理完毕!", udpState.counter);            Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));            sendDone.Set();        }        public static void Main()        {            AsyncUdpSever aus = new AsyncUdpSever();            Thread t = new Thread(new ThreadStart(aus.ReceiveMsg));            t.Start();            Console.Read();        }    }} 


[解决办法]
我做的局域网通信小例子,希望对你有用,Socket编程UDP协议

服务端

VB.NET code
 
Imports System.Net
Imports System.Net.Sockets

Public Class FormServer

Private socketServer As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Private receiveByte(10240) As Byte
Private receiveBuffer As New ClassLibraryMessage.Message
Private sendBuffer As New ClassLibraryMessage.Message
Private celintPoint As New IPEndPoint(IPAddress.Any, 0)
Private userList As New ClassLibraryMessage.Message

Private Sub FormServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BgWorkerListen.WorkerSupportsCancellation = True
BgWorkerListen.WorkerReportsProgress = True
BgWorkerListen.RunWorkerAsync()
End Sub

Private Sub FormServer_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
BgWorkerListen.CancelAsync()
End Sub

Private Sub BgWorkerListen_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BgWorkerListen.DoWork
'绑定服务器地址
socketServer.Bind(New IPEndPoint(IPAddress.Any, 6688))
While True
'接收信息
socketServer.ReceiveFrom(receiveByte, celintPoint)
'反序列化
receiveBuffer = PublicFunction.deserializeMessage(receiveByte)
'根据命令决定处理方式
Select Case receiveBuffer.order
Case "登录"
Dim i As Integer = userList.userName.IndexOf(receiveBuffer.name)
If i = -1 Then
'更新服务端用户列表
userList.userName.Add(receiveBuffer.name)
userList.userAdress.Add(celintPoint)
'返回登录信息
sendBuffer.order = "登录成功"
socketServer.SendTo(PublicFunction.serializeMessage(sendBuffer), celintPoint)
'刷新客户端用户列表
For j As Integer = 0 To userList.userName.Count - 1
sendBuffer = userList
sendBuffer.order = "刷新客户端列表"
socketServer.SendTo(PublicFunction.serializeMessage(sendBuffer), userList.userAdress(j))
Next
BgWorkerListen.ReportProgress(1)
Else
sendBuffer.order = "用户名重复"
socketServer.SendTo(PublicFunction.serializeMessage(sendBuffer), celintPoint)
End If
Case "发送消息"
For i As Integer = 0 To userList.userName.Count - 1
If userList.userName(i) = receiveBuffer.sendTo Then
sendBuffer = receiveBuffer
sendBuffer.order = "接收消息"
socketServer.SendTo(PublicFunction.serializeMessage(sendBuffer), userList.userAdress(i))


Exit Select
End If
Next
Case "退出"
'更新服务端用户列表
For i As Integer = 0 To userList.userName.Count - 1
If userList.userName(i) = receiveBuffer.name Then
userList.userName.RemoveAt(i)
userList.userAdress.RemoveAt(i)
Exit For
End If
Next
'将下线消息通知每一个客户端
sendBuffer.order = "下线"
sendBuffer.logoutName = receiveBuffer.name
For j As Integer = 0 To userList.userName.Count - 1
socketServer.SendTo(PublicFunction.serializeMessage(sendBuffer), userList.userAdress(j))
Next
BgWorkerListen.ReportProgress(1)
Case Else

End Select
End While
End Sub

Private Sub BgWorkerListen_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BgWorkerListen.ProgressChanged
Select Case e.ProgressPercentage
Case 1
ListUser.Items.Clear()
For i As Integer = 0 To userList.userName.Count - 1
ListUser.Items.Add(userList.userName(i) & "------" & userList.userAdress(i).Address.ToString & "------" & userList.userAdress(i).Port)
Next
Case Else

End Select
End Sub
End Class



序列化与饭序列化模块

VB.NET code
Module PublicFunction    Public Function serializeMessage(ByVal messaging As Object) As Object        Dim messageSerialize As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter        Dim messageMemoryStream As New System.IO.MemoryStream        Dim messageByte() As Byte        messageSerialize.Serialize(messageMemoryStream, Messaging)        messageMemoryStream.Position = 0        ReDim messageByte(messageMemoryStream.Length - 1)        messageMemoryStream.Read(messageByte, 0, messageMemoryStream.Length)        Return (messageByte)    End Function    Public Function deserializeMessage(ByVal messageByte As Object) As Object        Dim messageSerialize As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter        Dim messageMemoryStream As New System.IO.MemoryStream        messageMemoryStream.Write(MessageByte, 0, MessageByte.Length)        messageMemoryStream.Position = 0        Return (messageSerialize.Deserialize(messageMemoryStream))    End FunctionEnd Module
[解决办法]
客户端

VB.NET code
 
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading

Public Class FormCelint

'窗体闪动的API函数
Public Declare Sub FlashWindow Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal bInvert As Boolean)
'客户端Socket对象
Private socketCelint As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
'服务器IP及端口号
Private serverPoint As IPEndPoint


'发送内容
Private sendBuffer As New ClassLibraryMessage.Message
'接收字节数组
Private receiveByte(10240) As Byte
'接收内容
Private receiveBuffer As New ClassLibraryMessage.Message

Private Sub FormCelint_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BgWorkerListen.WorkerReportsProgress = True
BgWorkerListen.WorkerSupportsCancellation = True
End Sub

Private Sub FormCelint_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If GroupLogin.Enabled = False Then
'发送下线信息
sendBuffer.order = "退出"
sendBuffer.name = TextName.Text
socketCelint.SendTo(PublicFunction.serializeMessage(sendBuffer), serverPoint)
BgWorkerListen.CancelAsync()
End If
End Sub

Private Sub ButtonConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonConnect.Click
'发送登录请求
serverPoint = New IPEndPoint(IPAddress.Parse(TextIP.Text), TextPort.Text)
sendBuffer.order = "登录"
sendBuffer.name = TextName.Text
socketCelint.SendTo(PublicFunction.serializeMessage(sendBuffer), serverPoint)
'开启监听线程
If BgWorkerListen.IsBusy = False Then
BgWorkerListen.RunWorkerAsync()
End If
End Sub

Private Sub ButtonSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSend.Click
If TextSendTo.Text = String.Empty Then
MsgBox("小妹妹,你想和谁聊啊??")
ElseIf TextSendTo.Text = TextName.Text Then
MsgBox("猪头!跟自己聊有啥意思啊??")
Else
'发送聊天信息
sendBuffer.order = "发送消息"
sendBuffer.name = TextName.Text
sendBuffer.sendTo = TextSendTo.Text
sendBuffer.text = RichTextSend.Text
RichTextReceived.Text = RichTextReceived.Text & "你对" & TextSendTo.Text & "说:" & RichTextSend.Text & vbCrLf
socketCelint.SendTo(PublicFunction.serializeMessage(sendBuffer), serverPoint)
RichTextSend.Text = String.Empty
'将文本框滚动条保持在最下方
RichTextReceived.Select(RichTextReceived.Text.Length, 0)
RichTextReceived.ScrollToCaret()
End If
End Sub

Private Sub ListUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListUser.Click
If ListUser.SelectedItem IsNot Nothing Then
TextSendTo.Text = ListUser.SelectedItem.ToString
End If
End Sub

Private Sub BgWorkerListen_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BgWorkerListen.DoWork
While True
'接收信息
socketCelint.ReceiveFrom(receiveByte, 0, receiveByte.Length, SocketFlags.None, serverPoint)
'反序列化接收到的信息
receiveBuffer = PublicFunction.deserializeMessage(receiveByte)
Select Case receiveBuffer.order
Case "登录成功"
BgWorkerListen.ReportProgress(1)


Case "用户名重复"
BgWorkerListen.ReportProgress(2)
Case "刷新客户端列表"
BgWorkerListen.ReportProgress(3)
Case "接收消息"
BgWorkerListen.ReportProgress(4)
Case "下线"
BgWorkerListen.ReportProgress(5)
Case Else
End Select
End While
End Sub

Private Sub BgWorkerListen_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BgWorkerListen.ProgressChanged
Select Case e.ProgressPercentage
Case 1
'登录成功
GroupLogin.Enabled = False
GroupMessage.Enabled = True
Case 2
'用户名重复
MsgBox("用户名重复!")
Case 3
'获取客户端列表
ListUser.Items.Clear()
For i As Integer = 0 To receiveBuffer.userName.Count - 1
ListUser.Items.Add(receiveBuffer.userName(i))
Next
Case 4
'显示消息
RichTextReceived.Text = RichTextReceived.Text & receiveBuffer.name & "对你说:" & receiveBuffer.text & vbCrLf
'将文本框滚动条保持在最下方
RichTextReceived.Select(RichTextReceived.Text.Length, 0)
RichTextReceived.ScrollToCaret()
'窗体闪动
FlashWindow(Me.Handle, True)
Case 5
'处理用户下线信息
ListUser.Items.Remove(receiveBuffer.logoutName)
If TextSendTo.Text = receiveBuffer.logoutName Then
TextSendTo.Text = String.Empty
End If
Case Else

End Select
End Sub
End Class



公用类库

VB.NET code
Imports System.Net<Serializable()> Public Class Message    Public order As String    Public name As String    Public sendTo As String    Public logoutName As String    Public text As String    Public userName As New ArrayList    Public userAdress As New ArrayListEnd Class
[解决办法]
ls写的这段代码挺不错呀,呵呵。
学习一下喽
[解决办法]
太强了csharp还要好好学了才能看懂啊
[解决办法]
帮顶
[解决办法]
帮顶
[解决办法]
UP
[解决办法]
探讨
客户端


VB.NET code
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading

Public Class FormCelint

'窗体闪动的API函数
Public Declare Sub FlashWindow Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal bInvert As Boolean)
'客户端Socket对象
Private socketCelint As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)


'服务器IP及端…

读书人网 >VB Dotnet

热点推荐