The client communicates with the server by IP (identifying the host) + port number (identifying the application).
IP Address Query method: Windows+r key, input cmd, input ipconfig.
Port number: Can be set by itself, but usually 4 bits.
Server-side:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading.Tasks;
Namespace _021_socket Programming _tcp protocol
{
Class Program
{
static void Main (string[] args)
{
Socket tcpserver = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); TCP protocol
ip+ Port number: IP indicates which computer to communicate with, port number (typically 4-bit) indicates which application
IPAddress IPAddress = new IPAddress (new byte[] {192, 168, 43, 231});
EndPoint point = new IPEndPoint (ipaddress, 7788);
Tcpserver.bind (point);
Tcpserver.listen (100);
Console.WriteLine ("Start Monitoring");
Socket clientsocket = tcpserver.accept ();//Pause the current thread until a client connects to it, then make the following code
Console.WriteLine ("A client is connected");
string message1 = "Hello welcomes You";
byte[] data1 = Encoding.UTF8.GetBytes (message1);
Clientsocket.send (DATA1);
Console.WriteLine ("Send a piece of data to the client");
byte[] data2 = new byte[1024];//Create a byte array to do the container, to undertake the data sent by the client
int length = clientsocket.receive (DATA2);
String message2 = Encoding.UTF8.GetString (data2, 0, length);//convert byte data to a string
Console.WriteLine ("received a message sent from the client:" + message2);
Console.readkey ();
}
}
}
Client:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading.Tasks;
Namespace _001_socket Programming _tcp Protocol _ Client
{
Class Program
{
static void Main (string[] args)
{
Socket tcpClient = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
IPAddress IPAddress = Ipaddress.parse ("192.168.43.231");
EndPoint point = new IPEndPoint (ipaddress, 7788);
Tcpclient.connect (point);
byte[] data = new byte[1024];
int length = tcpclient.receive (data);
String message = Encoding.UTF8.GetString (data, 0, length);
Console.WriteLine (message);
Send messages to server side
String message2 = Console.ReadLine ();//Client input data
Tcpclient.send (Encoding.UTF8.GetBytes (Message2));//Convert a string into a byte array and send it to the server side
Console.readkey ();
}
}
}
Note: To implement client-to-server communication, you should establish a project for it, and you should run the server first.
C#SOCKET_TCP (client, server-side communication)