I recently used. NET socket to develop an IM component similar to QQ. I first wrote a static class for sending and receiving Udp messages! It is not perfect either. It is reserved for the moment and used for reconstruction in the future!
Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Namespace XChatLib
{
/** // <Summary>
/// MessageUtility message tool class, which is a static tool class.
/// </Summary>
Public class MessageUtility
{
// Default port number
Private const int DEFAULT_PORT = 9050;
Private MessageUtility ()
{
//
// TODO: add the constructor logic here
//
}
// Message sending Method
Public static void SendMessage (string msg)
{
Byte [] data = new byte [1024];
// Host information of the Local Machine
IPHostEntry host = Dns. GetHostByName (Dns. GetHostName ());
// The port number parameter can be used to read the port number from the configuration file after reconstruction.
IPEndPoint ipep = new IPEndPoint (host. AddressList [0], DEFAULT_PORT );
// Create a udp socket
Socket server = new Socket (AddressFamily. InterNetwork,
SocketType. Dgram, ProtocolType. Udp );
If (msg. Length! = 0)
{
Data = Encoding. Unicode. GetBytes (msg );
Try
{
Server. SendTo (data, data. Length, SocketFlags. None, ipep );
}
Catch (SocketException ){}
Finally
{
Server. Close ();
}
}
}
// Message receiving Method
Public static string ReceiveMessage ()
{
Int recv;
Byte [] data = new byte [1024];
// Create a random endpoint object
IPEndPoint ipep = new IPEndPoint (IPAddress. Any, DEFAULT_PORT );
// Create a Udp socket
Socket newsock = new Socket (
AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
// Bind the random endpoint to the Udp socket to wait for incoming packets
Newsock. Bind (ipep );
// Create an endpoint for accepting arbitrary senders
IPEndPoint sender = new IPEndPoint (IPAddress. Any, 0 );
EndPoint tmpRemote = (EndPoint) (sender );
Try
{
Recv = newsock. ReceiveFrom (data, ref tmpRemote );
Return Encoding. Unicode. GetString (data, 0, data. Length );
}
Catch (SocketException)
{
Return null;
}
Finally
{
Newsock. Close (); // Close the socket to release resources
}
}
}
}