Client code
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. net;
Using system. net. Sockets;
Using system. Threading;
Namespace socketclient
{
Class Program
{
Static void main (string [] ARGs)
{
// Save the input string to be sent
String input;
// Remote IP address to be connected
IPaddress remotehost = IPaddress. parse ("172.16.86.90 ");
// Combination of IP addresses and ports
Ipendpoint IEP = new ipendpoint (remotehost, 8080 );
// Bind the address to the socket
Socket clientsocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
// Connect to the remote server
Try
{
Clientsocket. Connect (IEP );
Console. writeline ("Enter the string you want to send ");
// Save the input string
Input = console. Readline ();
// Use a byte array to save the string to be sent
Byte [] Message = system. Text. encoding. Unicode. getbytes (input );
// Create a new networkstream object to send data
Networkstream netstream = new networkstream (clientsocket );
// Send message content to the server
Netstream. Write (message, 0, message. Length );
Clientsocket. Shutdown (socketshutdown. Both );
Clientsocket. Close ();
}
Catch (system. Exception ex)
{
Console. writeline ("server connection failed ");
}
}
}
}
Server code
Code
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. net;
Using system. net. Sockets;
Using system. Threading;
Namespace socketserver
{
Class Program
{
Static void main (string [] ARGs)
{
// Local IP Address
IPaddress IP = IPaddress. parse ("172.16.86.90 ");
// Combination of IP addresses and ports
Ipendpoint IEP = new ipendpoint (IP, 8080 );
// Create a socket
Socket socket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
// Bind a socket
Socket. BIND (IEP );
// The server is ready to receive any connection
Socket. Listen (10 );
While (true)
{
// Execute the accept Method
Socket Client = socket. Accept ();
Byte [] Message = new byte [1024];
Networkstream = new networkstream (client );
Int Len = networkstream. Read (message, 0, message. Length );
// Convert byte array to string
String output = system. Text. encoding. Unicode. getstring (Message );
Console. writeline ("received from the client" + Len. tostring () + "bytes. Received string: "+ output );
}
}
}
}