Реализация UDP на C#
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace LidTest
{
class MainClass
{
static UdpClient usck;
static void recv(IAsyncResult res) {
IPEndPoint remote = new IPEndPoint(IPAddress.Any,0);
byte[] data = usck.EndReceive(res, ref remote);
// do something with data received from remote
Console.WriteLine(remote.Address.ToString() + ": " + Encoding.ASCII.GetString(data));
// get next packet
usck.BeginReceive(recv, null);
}
public static void Main (string[] args)
{
usck = new UdpClient("localhost",12000);
Console.WriteLine("waiting for packets, hit enter to stop");
usck.BeginReceive(new AsyncCallback(recv), null);
//usck.Send(new byte[] {1,2,3} , 3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write((Int16)(2));
bw.Write("ПИП");
bw.Write((Int16)(4));
bw.Write(true);
bw.Flush();
byte[] b =ms.ToArray();
usck.Send(b,b.Length);
Console.ReadLine();
usck.Close();
}
}
}
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace LidTest
{
class MainClass
{
static UdpClient usck;
static void recv(IAsyncResult res) {
IPEndPoint remote = new IPEndPoint(IPAddress.Any,0);
byte[] data = usck.EndReceive(res, ref remote);
// do something with data received from remote
Console.WriteLine(remote.Address.ToString() + ": " + Encoding.ASCII.GetString(data));
// get next packet
usck.BeginReceive(recv, null);
}
public static void Main (string[] args)
{
usck = new UdpClient("localhost",12000);
Console.WriteLine("waiting for packets, hit enter to stop");
usck.BeginReceive(new AsyncCallback(recv), null);
//usck.Send(new byte[] {1,2,3} , 3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write((Int16)(2));
bw.Write("ПИП");
bw.Write((Int16)(4));
bw.Write(true);
bw.Flush();
byte[] b =ms.ToArray();
usck.Send(b,b.Length);
Console.ReadLine();
usck.Close();
}
}
}
Комментариев нет:
Отправить комментарий