求异步UDP实例

afqitx 2009-05-20 11:24:59
要效率高点的,从未做过多线程的东西,请大家尽量详细些
...全文
471 21 打赏 收藏 转发到动态 举报
写回复
用AI写文章
21 条回复
切换为时间正序
请发表友善的回复…
发表回复
vb_net_2012 2012-07-04
  • 打赏
  • 举报
回复
我也想找这方面的代码,看不懂、、、
ichinaec 2009-09-26
  • 打赏
  • 举报
回复
看看,小气
afqitx 2009-07-02
  • 打赏
  • 举报
回复
谢谢哈,最近忙个小项目,改天试试!
lazyboysqaz 2009-06-25
  • 打赏
  • 举报
回复
UP
ScottYj 2009-06-25
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 blues_zhao_yang 的回复:]
客户端


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及端…
[/Quote]
D
kangbo818 2009-06-24
  • 打赏
  • 举报
回复
帮顶
kangbo818 2009-06-24
  • 打赏
  • 举报
回复
帮顶
ihi733521 2009-06-14
  • 打赏
  • 举报
回复
太强了csharp还要好好学了才能看懂啊
blues_zhao_yang 2009-05-27
  • 打赏
  • 举报
回复
客户端


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


公用类库


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 ArrayList
End Class
blues_zhao_yang 2009-05-27
  • 打赏
  • 举报
回复
我做的局域网通信小例子,希望对你有用,Socket编程UDP协议

服务端


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


序列化与饭序列化模块


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 Function
End Module
wzuomin 2009-05-27
  • 打赏
  • 举报
回复
ls写的这段代码挺不错呀,呵呵。
学习一下喽
afqitx 2009-05-26
  • 打赏
  • 举报
回复
各位高人帮我看看!
afqitx 2009-05-22
  • 打赏
  • 举报
回复
c# 还是不懂,我找了一个
http://www.cnblogs.com/yyshenren/archive/2008/07/10/1240114.html
大伙看看这个效率怎么样?
afqitx 2009-05-21
  • 打赏
  • 举报
回复
C#不太熟,好像还是有点错误!
zzxap 2009-05-21
  • 打赏
  • 举报
回复
[CODE=C#]
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncClient
{
public class UdpState
{
public UdpClient udpClient = null;
public IPEndPoint ipEndPoint = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public int counter = 0;
}
public class AsyncUdpClient
{
public static bool messageSent = false;
// Receive a message and write it to the console.
private const int listenPort = 1101;
private const int remotePort = 1100;
private IPEndPoint localEP = null;
private IPEndPoint remoteEP = null;
private UdpClient udpReceive = null;
private UdpClient udpSend = null;
private UdpState udpSendState = null;
private UdpState udpReceiveState = null;
private int counter = 0;
private ManualResetEvent sendDone = new ManualResetEvent(false);
private ManualResetEvent receiveDone = new ManualResetEvent(false);
private Socket receiveSocket;
private Socket sendSocket;
public AsyncUdpClient()
{
localEP = new IPEndPoint(IPAddress.Any, listenPort);
remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0],remotePort);
udpReceive = new UdpClient(localEP);
udpSend = new UdpClient();

udpSendState = new UdpState();
udpSendState.ipEndPoint = remoteEP;
udpSendState.udpClient = udpSend;

udpReceiveState = new UdpState();
udpReceiveState.ipEndPoint = remoteEP;
udpReceiveState.udpClient = udpReceive;

receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
receiveSocket.Bind(localEP);

sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sendSocket.Bind(remoteEP);
}
public void SendMsg()
{
udpSend.Connect(remoteEP);

//Thread t = new Thread(new ThreadStart(ReceiveMessages));
//t.Start();
Byte[] sendBytes;
string message;
while (true)
{
message = "Client" + (counter++).ToString();
lock (this)
{
sendBytes = Encoding.ASCII.GetBytes(message);
udpSendState.counter = counter;
udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
sendDone.WaitOne();
Thread.Sleep(200);
ReceiveMessages();
}
}
}

public void SendCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Console.WriteLine("第{0}个发送完毕!", udpState.counter);
Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
//if (udpState.counter == 10)
//{
// udpState.udpClient.Close();
//}
sendDone.Set();
}
}

public void ReceiveMessages()
{
lock (this)
{
udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
receiveDone.WaitOne();
Thread.Sleep(100);
}
}
public void ReceiveCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
string receiveString = Encoding.Unicode.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
receiveDone.Set();
}
}

public static void Main()
{
AsyncUdpClient auc = new AsyncUdpClient();
auc.SendMsg();
Console.Read();
}
}
}
[/CODE]
zzxap 2009-05-21
  • 打赏
  • 举报
回复
[code=C#]
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();
}
}
}

[/CODE]
wuyq11 2009-05-20
  • 打赏
  • 举报
回复
afqitx 2009-05-20
  • 打赏
  • 举报
回复
这个只是另外开了一个线程去接收跟发送,不是我想的,我是想开个线程接收数据,收到之后用另外一个线程处理,并发送数据
yanlongwuhui 2009-05-20
  • 打赏
  • 举报
回复
看看:http://download.csdn.net/source/1046138
afqitx 2009-05-20
  • 打赏
  • 举报
回复
这个只是发送的吧,我是要做服务用的,
如:
监听8000端口,收到数据之后用另外一个线程处理这样的
加载更多回复(1)

16,555

社区成员

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

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