Socket Server side:
1. Create a socket
Socket tcpClient = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//three parameters enumerated type (network), respectively Socket type, protocol
2. Binding IP and port number
IPAddress IPAddress = new IPAddress (new byte[] {192,168,119,1});
EndPoint Point =new IPEndPoint (ipaddress,8811);
TCPServer. Bind (point);//Bind method Bind (), IPEndPoint () encapsulates IP and port
3. Start monitoring
Tcpserver.listen (100);//parameter is the maximum number of connections
4. Receiving clients
Socket clientsocket= tcpserver.accept ();
5. Send a message to the client
String message = "Hello welcome!";
byte[] Date = Encoding.UTF8.GetBytes (message);//encoding () transcoding
Clientsocket.send (date);
6. Receiving Client Information
Byte[] Date2=new byte[1024];
int length = clientsocket.receive (Date2);
String message2 = Encoding.UTF8.GetString (date2, 0, length);
Console.WriteLine ("Client sends information over:" +message2);
Code:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Namespace Socketserver
{
Class Program
{
static void Main (string[] args)
{
Socket tcpserver =new socket (addressfamily.internetwork,sockettype.stream, protocoltype.tcp);
IPAddress IPAddress = new IPAddress (new byte[] {192,168,191,1});
EndPoint Point =new IPEndPoint (ipaddress,8811);
TCPServer. Bind (point);
Tcpserver.listen (100);
Console.WriteLine ("Start Monitoring");
Socket clientsocket= tcpserver.accept ();
Console.WriteLine ("A Client link");
String message = "Hello welcome!";
byte[] Date = Encoding.UTF8.GetBytes (message);
Clientsocket.send (date);
Byte[] Date2=new byte[1024];
int length = clientsocket.receive (Date2);
String message2 = Encoding.UTF8.GetString (date2, 0, length);
Console.WriteLine ("Client sends information over:" +message2);
Console.readkey ();
}
}
}
Socket Client
1. Create a socket
2. Initiating the request
Tcpclient.connect ();
3. Receiving server-side information
4. Send messages to server side
Code:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Namespace Socketclient
{
Class Program
{
static void Main (string[] args)
{
Socket tcpClient = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
IPAddress ipaddress=new IPAddress (New byte[]{192,168,191,1});
EndPoint Point =new IPEndPoint (ipaddress,8811);
Tcpclient.connect (point);
byte[] Date = new byte[1024];
int length= tcpclient.receive (date);
String message = Encoding.UTF8.GetString (date, 0, length);
Console.WriteLine ("Server-side sent message:" +message);
String message2 = Console.ReadLine ();
Tcpclient.send (Encoding.UTF8.GetBytes (message2));
Console.readkey ();
}
}
}
C # Socket network programming based on TCP protocol