Socket Communications Server in compliance with the basic process, first created Socket, then call Bind Bind IP address and port number, then call Listen to wait for client connections. The last call is received while loop Accept client connection, and respond to messages.
the System the using;
the using the System.Net;
the using the System.Net.Sockets; // the Socket class provides a rich set of methods and properties for network communications
test1 namespace
{
class MainClass
{
public static void the Main (String [] args)
{
Console.WriteLine ( "the Hello World!");
// the Socket
the Socket = new new listenfd the Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create a socket, the three parameters representing the address family, socket type (stream byte stream) protocol and
the IPAddress ipAdr = IPAddress.Parse ( "127.0.0.1");
// the Bind
the IPEndPoint = new new IPEP the IPEndPoint (ipAdr, 1234);
listenfd.Bind (IPEP); // bind to the socket listenfd ip and port
// Listern
listenfd.Listen (0); // open the monitor, the specified queue backlog parameter can accommodate up awaiting number of connections, 0 means no limitation
Console.WriteLine ( "[server] started successfully");
the while (to true)
{
Accept //
the Socket connfd listenfd.Accept = (); // server receives the client connection
Console.WriteLine ( "[Server] the Accept");
// Recv
byte [] = readBuff new new byte [1024]; // store the received data
int count = connfd.Receive (readBuff); // length server receives client data, the return value indicating the received data
string str = System.Text.Encoding.UTF8.GetString (readBuff, 0 , count) ; // the byte [] array into a string displayed on the screen
Console.WriteLine ( "[server receives a]" + STR);
// Send
byte [] bytes = System.Text.Encoding.Default.GetBytes ( "Serv echo "+ str); // server converts the string to byte [] array
connfd.Send (bytes); // send data to the client server
}
}
}
}