Simple Network Communication Based on TCP Socket

Source: Internet
Author: User

This instance is a simple TCP-based communication instance, which can be divided into server and client. The server listens to client connection requests and the client sends information to the server, the server replies to the information sent by the client for communication testing:

The server code is as follows:

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Net;
Using System. Net. Sockets;

Namespace SimpleTcpServer
{
Class Program
{
Static void Main (string [] args)
{
// Received data
Int receive;
// Define the data buffer
Byte [] date = new byte [1024];
// Set the client connection to receive any request from the IP address of the client terminal
IPEndPoint MyIpEndpoint = new IPEndPoint (IPAddress. Any, 13000 );
// Create a server socket
Socket MySocket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
// Bind a server socket
MySocket. Bind (MyIpEndpoint );
// Listen
MySocket. Listen (10 );
Console. WriteLine ("Waitting for a message from client! ");

// Obtain the client socket
Socket Client = MySocket. Accept ();
// Obtain the client endpoint
IPEndPoint ClientEndPoint = (IPEndPoint) Client. RemoteEndPoint;
Console. WriteLine ("Connect with {0} port {1}", ClientEndPoint. Address, ClientEndPoint. Port. ToString ());

// Encode the information to be sent to the client
Date = Encoding. ASCII. GetBytes ("Welcome to my Server ");
// Send information to the client
Client. Send (date, date. Length, SocketFlags. None );

// If the length of received information is 0, the loop is automatically exited.
While (true)
{
Receive = Client. Receive (date );
If (receive = 0)
{
Break;
}
// Received characters
String ReceiveString = Encoding. UTF8.GetString (date, 0, receive );
Console. WriteLine (ReceiveString );
// Send information to the client
Client. Send (date, receive, SocketFlags. None );
}
Console. WriteLine ("DisConnected with {0}", ClientEndPoint. Address );
Client. Close ();
MySocket. Close ();
}
}
}

 

The client code is as follows:

 

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Net;
Using System. Net. Sockets;

Namespace SimpleTcpClient
{
Class Program
{
Static void Main (string [] args)
{
// Buffer size
Byte [] data = new byte [1024];
String Input, StringData;
Int receive;
// Set the connection terminal
IPEndPoint MyIpEndpoint = new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 13000 );
// Set the socket used to connect to the server
Socket MyServer = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Try
{
// Connect to the server
MyServer. Connect (MyIpEndpoint );
}
Catch
{
Console. WriteLine ("Fail to connect to the server! ");
Return;
}
// Receives information from the server.
Receive = MyServer. Receive (data );
// Transcode the sent information
StringData = Encoding. UTF8.GetString (data, 0, receive );
Console. WriteLine (StringData );

While (true)
{
// Input information from the client
Input = Console. ReadLine ();
If (Input = "exit ")
{
Break;
}
// Send the message to the server
MyServer. Send (Encoding. UTF8.GetBytes (Input ));
// Receive Server Information
Receive = MyServer. Receive (data );
StringData = Encoding. UTF8.GetString (data, 0, receive );
Console. WriteLine ("Server: {0}", StringData );
}
// Release resources
Console. WriteLine ("Disneccted from Server! ");
MyServer. Shutdown (SocketShutdown. Both );
MyServer. Close ();
}
}
}

 

This example is TCP-based synchronous network communication. We will continue to learn TCP-based Asynchronous Network Communication later. The advantages of synchronous network communication are simple and easy to understand. In the case of a small amount of communication, the efficiency of synchronous communication is higher than that of asynchronous communication, but the disadvantages of synchronous communication are also obvious.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.