socket client and server in csharp

To create a basic client-server program using sockets in C#, you can follow these steps:

  1. Create a server socket:
main.cs
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
100 chars
2 lines
  1. Bind the server socket to a specific IP address and a port number:
main.cs
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234)); 
57 chars
2 lines
  1. Start listening for incoming connections:
main.cs
serverSocket.Listen(1); 
25 chars
2 lines
  1. Create a client socket when a connection is accepted by the server:
main.cs
Socket clientSocket = serverSocket.Accept(); 
46 chars
2 lines
  1. Send and receive data between the client and server using the socket's Send and Receive methods:
main.cs
// Send data from server to client 
byte[] data = Encoding.ASCII.GetBytes("Hello from server!"); 
clientSocket.Send(data);

// Receive data from client 
byte[] buffer = new byte[1024]; 
int bytesRead = clientSocket.Receive(buffer); 
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead); 
299 chars
9 lines
  1. Close the client and server sockets when done:
main.cs
clientSocket.Shutdown(SocketShutdown.Both); 
clientSocket.Close(); 
serverSocket.Close(); 
91 chars
4 lines

gistlibby LogSnag