biGpython

生亦何欢,死亦何苦? 予我長袖,我必善舞!

导航

.net Csharpt C# UDP 异步发送信息 代码实例

接受端:

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
/*异步接受类,并异步响应*/
namespace HostBackupReciever
{
class UpdData
{
public UdpClient u = null;
public IPEndPoint p = null;
}

public class Receive2
{
private bool msgGet = false;

public void Receive()
{
IPEndPoint p = new IPEndPoint(IPAddress.Any,11000);
UdpClient u = new UdpClient(p);
u.BeginReceive(new AsyncCallback(ReceiveCallback),u);
}

public void ReceiveCallback(IAsyncResult result)
{
UdpClient u = (UdpClient)result.AsyncState;
IPEndPoint p = new IPEndPoint(IPAddress.Any, 11000);
Console.WriteLine("正在接收中.....");
Thread.Sleep(6000);
byte[] recvData = u.EndReceive(result, ref p);
string rData = Encoding.Default.GetString(recvData);
Console.WriteLine(rData);
msgGet = true;
if (msgGet)
{
string respMsg = "这是服务器响应信息";
byte[] respDate = Encoding.Default.GetBytes(respMsg);

u.BeginSend(respDate, respDate.Length, p,new AsyncCallback(SendCallback), u);
}
u.BeginReceive(new AsyncCallback(ReceiveCallback), u);

}

public void SendCallback(IAsyncResult result)
{
UdpClient u = (UdpClient)result.AsyncState;
Console.WriteLine("已经发送的字节数位:" + u.EndSend(result));
}

public static void Main(string[] args)
{
Receive2 r2 = new Receive2();
r2.Receive();
Console.ReadKey();
}
}


}

发送端:

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketPros
{
class Sender2
{
public void Send(string server,string msg)
{
UdpClient u = new UdpClient(12000);
IPEndPoint p = new IPEndPoint(IPAddress.Parse(server), 11000);

byte[] sendData = Encoding.Default.GetBytes(msg);
u.BeginSend(sendData, sendData.Length,p, new AsyncCallback(SendCallback), u);

byte[] sendData2 = Encoding.Default.GetBytes("第二次发送");
u.BeginSend(sendData2, sendData2.Length, p, new AsyncCallback(SendCallback), u);

u.BeginReceive(new AsyncCallback(ReceiveCallback), u);
}

public void ReceiveCallback(IAsyncResult result)
{
UdpClient u = (UdpClient)result.AsyncState;
IPEndPoint p = new IPEndPoint(IPAddress.Any, 11000);
Console.WriteLine("正在接收服务器响应信息中.....");
Thread.Sleep(2000);
byte[] recvData = u.EndReceive(result, ref p);
string rData = Encoding.Default.GetString(recvData);
Console.WriteLine("sender接收到的服务器的respMsg" + rData);

u.BeginReceive(new AsyncCallback(ReceiveCallback), u);

}

public void SendCallback(IAsyncResult result)
{

UdpClient u = (UdpClient)result.AsyncState;
Console.WriteLine("已经发送的字节数位:" + u.EndSend(result));
//msgSent = true;
}

public static void Main(string[] args)
{
Sender2 s2 = new Sender2();
s2.Send("127.0.0.1","what a fucking code!!!!");
Console.ReadKey();
}
}
}

代码仅供参考

posted on 2012-03-06 18:08  biGpython  阅读(1136)  评论(0编辑  收藏  举报