本demo使用C#編寫,采用UDP協議。
分別建立發送、接收線程循環阻塞處理相應任務。
[csharp]
using System;
//using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPChat
{
class Program
{
static void Main(string[] args)
{
//IPAddress[] t = Dns.GetHostAddresses(Dns.GetHostName());//在不同的局域網中獲取的數量不一,請調試甄別
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString().Length > 6 ? Dns.GetHostAddresses(Dns.GetHostName())[0] : Dns.GetHostAddresses(Dns.GetHostName())[1];
IPEndPoint local = new IPEndPoint(ip, 8001);
bool isAlive = true;
UdpClient c= new UdpClient(local);
Thread s = new Thread(() => tSend(ref isAlive, c));//發送線程
s.Start();
Thread r = new Thread(() => tRcv(ref isAlive, c));//接受線程
r.Start();
}
static void tSend(ref bool isAlive, UdpClient c)
{
string input;
byte[] send;
IPEndPoint remote = null;
bool isAnIp = false;
while (!isAnIp)
{
Console.WriteLine("pls input an ip for this chat.");
input = Console.ReadLine();
try
{
remote = new IPEndPoint(IPAddress.Parse(input), 503);
isAnIp = true;
}
catch
{
Console.WriteLine("it is an invalid ip.\r\n");
}
}
while (isAlive)
{
input = Console.ReadLine();
if (input == "exit")
isAlive = false;
send=Encoding.UTF8.GetBytes(input);
c.Send(send, send.Length, remote);
Console.WriteLine();
Console.WriteLine("{0} sent:{1}", DateTime.Now.ToLocalTime().ToShortTimeString(), input);
}
c.Close();
Console.WriteLine("quit chat.");
Console.ReadLine();
}
static void tRcv(ref bool isAlive, UdpClient c)
{
byte[] rcv;
string receive;
IPEndPoint remote = new IPEndPoint(IPAddress.Any,0);
while (isAlive)
{
try
{
rcv = c.Receive(ref remote);
}
catch
{
break;
}
receive=Encoding.UTF8.GetString(rcv);
if (receive != "exit")
{
Console.WriteLine("{0} received:{1}", DateTime.Now.ToLocalTime().ToShortTimeString(), receive);
}
else
{
Console.WriteLine("{0} quitted.",remote.Address.ToString());
}
}
}
}
}