UDPServer
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SimpleUdpSrvr
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定義一網絡端點
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定義一個Socket
newsock.Bind(ipep);//Socket與本地的一個終結點相關聯
Console.WriteLine("Waiting for a clIEnt..");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定義要發送的計算機的地址
EndPoint Remote = (EndPoint)(sender);//
recv = newsock.ReceiveFrom(data, ref Remote);//接受數據
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetBytes(data,0,recv));
string welcome = "Welcome to my test server!";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
while (true)
{
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
}
}
UDPClIEnt
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SimpleUdpClIEnt
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[1024];//定義一個數組用來做數據的緩沖區
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello,are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);//將數據發送到指定的終結點
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);//接受來自服務器的數據
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true)//讀取數據
{
input = Console.ReadLine();//從鍵盤讀取數據
if (input == "text")//結束標記
{
break;
}
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//將數據發送到指定的終結點Remote
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);//從Remote接受數據
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping clIEnt");
server.Close();
}
}
}
上面的示例只是簡單的應用了socket來實現通信,你也可以實現異步socket、IP組播 等等。
MS還為我們提供了幾個助手類:TcpClient類、TcpListener類、UDPClIEnt類。這幾個類簡化了一些操作,所以你也可以利用這幾類來寫上面的代碼,但我個人還是比較習慣直接用socket來寫。
既然快寫完了,那我就再多啰嗦幾句。在需要即時響應的軟件中,我個人更傾向使用UDP來實現通信,因為相比TCP來說,UDP占用更少的資源,且響應速度快,延時低。至於UDP的可靠性,則可以通過在應用層加以控制來滿足。當然如果可靠性要求高的環境下,還是建議使用TCP。