This demo uses C # and UDP protocol.
The sending and receiving threads are set up to process the corresponding tasks cyclically.
[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
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); // The sending Thread
S. Start ();
Thread r = new Thread () => tRcv (ref isAlive, c); // receives the Thread
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 (). to1_timestring (), 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 ());
}
}
}
}
}