-----
Server端:
class ServerReceive
{
static void Main(string[] args)
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 8000);
Socket s = new Socket(endPoint.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
// Creates an IPEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderRemote = (EndPoint)sender;
// Binding is required with ReceiveFrom calls.
s.Bind(endPoint);
byte[] msg = new Byte[20]; // Buffer
Console.WriteLine("Waiting to receive datagrams from client...");
while(Console.KeyAvailable == false)
{
// This call blocks.
s.Receive(msg);
//s.ReceiveFrom(msg, ref senderRemote);
Console.WriteLine("\n接收到的字串: " + Encoding.ASCII.GetString(msg));
}
s.Close();
}
}
Client端:
class ClientSend
{
static void Main(string[] args)
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 8000);
Socket s = new Socket(endPoint.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes("This is a test");
Console.WriteLine("Sending data.");
// This call blocks.
s.SendTo(msg, endPoint);
s.Close();
}
}
沒有留言:
張貼留言