With the accumulation of notes (2), udp is much simpler.
Code
# Region usings
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;
# Endregion
Namespace NetStudy
{
Delegate void AppendItem (object o );
Public partial class MyTalkUdp: Form
{
# Region Vars
Thread serverThread;
EndPoint remoteIpep;
Socket serverSock, clicentSock;
AppendItem AddItem;
Void addItem (object o)
{
ListBox. Items. Add (o );
}
String message;
# Endregion
# Region Constructions
Public MyTalkUdp ()
{
InitializeComponent ();
AddItem = new AppendItem (addItem );
}
# Endregion
# Region Events
Private void btSent_Click (object sender, EventArgs e)
{
IPAddress [] ipalist = Dns. GetHostAddresses (txtTarget. Text. Trim ());
If (ipalist. GetLength (0) <= 0)
{
ListBox. Items. Add ("Invalid Target! ");
Return;
}
IPAddress ipa = ipalist [0];
RemoteIpep = new ipendpoints (ipa, 8989 );
Message = txtMessage. Text;
TxtMessage. Clear ();
SentMessage ();
ListBox. Items. Add ("TO" + remoteIpep. ToString () + ":" + message );
}
Private void MyTalkUdp_Load (object sender, EventArgs e)
{
ServerThread = new Thread (new ThreadStart (StartListen ));
ServerThread. Start ();
}
# Endregion
# Region Methods
Void StartListen ()
{
ServerSock = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
ServerSock. Bind (new IPEndPoint (IPAddress. Any, 8989 ));
Byte [] buf = new byte [1, 1024];
IPEndPoint remotePoint = null;
Int bufLen = 0;
Bool isKeepAlive = true;
String data;
While (isKeepAlive)
{
Try
{
BufLen = serverSock. Available;
If (bufLen! = 0)
{
ServerSock. ReceiveFrom (buf, SocketFlags. None, ref remoteIpep );
Data = System. Text. Encoding. Unicode. GetString (buf, 0, bufLen );
If (! String. IsNullOrEmpty (data ))
{
ListBox. Invoke (AddItem, "FROM" + remoteIpep. ToString () + ":" + data );
}
}
}
Catch (SocketException sexc)
{
ListBox. Invoke (AddItem, sexc. Message );
}
}
}
Void SentMessage ()
{
If (string. IsNullOrEmpty (message) return;
Byte [] buf = new byte [1, 1024];
Buf = System. Text. Encoding. Unicode. GetBytes (message );
ClicentSock = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
Try
{
ClicentSock. SendTo (buf, remoteIpep );
}
Catch (SocketException sexc)
{
ListBox. Items. Add (sexc. Message );
}
}
# Endregion
}
}