C # socket simple example (communication between the server and the client)

Source: Internet
Author: User

This example simply shows how to use the socket class to implement connection-oriented communication.

Note: The purpose of this example is to explain the general idea of writing a program using socket, rather than the actual project. In this example, there are still many unsolved problems, such as the message boundary problem, whether the port number is occupied, and the message Command Parsing problem ..

The following is the code of two programs (both of them are console programs)

The complete server code is as follows:

 

Introduce namespace:

using System.Net.Sockets;  
using System.Net;
using System.Threading;

 

The complete code is as follows:

Namespace socketserver
{
Class Program
{
Private Static byte [] result = new byte [1, 1024];
Private Static int myprot = 8885; // Port
Static socket serversocket;
Static void main (string [] ARGs)
{
// Server IP Address
IPaddress IP = IPaddress. parse ("127.0.0.1 ");
Serversocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Serversocket. BIND (New ipendpoint (IP, myprot); // bind an IP Address: Port
Serversocket. Listen (10); // you can specify up to 10 queued connection requests.
Console. writeline ("listener started {0} succeeded", serversocket. localendpoint. tostring ());
// Send data through clientsoket
Thread mythread = new thread (listenclientconnect );
Mythread. Start ();
Console. Readline ();
}

/// <Summary>
/// Listen for client connection
/// </Summary>
Private Static void listenclientconnect ()
{
While (true)
{
Socket clientsocket = serversocket. Accept ();
Clientsocket. Send (encoding. ASCII. getbytes ("server say hello "));
Thread receivethread = new thread (receivemessage );
Receivethread. Start (clientsocket );
}
}

/// <Summary>
/// Receive messages
/// </Summary>
/// <Param name = "clientsocket"> </param>
Private Static void receivemessage (Object clientsocket)
{
Socket myclientsocket = (socket) clientsocket;
While (true)
{
Try
{
// Receive data through clientsocket
Int receivenumber = myclientsocket. Receive (result );
Console. writeline ("receiving client {0} message {1}", myclientsocket. remoteendpoint. tostring (), encoding. ASCII. getstring (result, 0, receivenumber ));
}
Catch (exception ex)
{
Console. writeline (ex. Message );
Myclientsocket. Shutdown (socketshutdown. Both );
Myclientsocket. Close ();
Break;
}
}
}
}
}

The above is the complete code of the server.

 

The complete code of the client is as follows:

 

Introduce namespace:

using System.Net;  
using System.Net.Sockets;
using System.Threading;

 

Complete code:

Namespace socketclient
{
Class Program
{
Private Static byte [] result = new byte [1, 1024];
Static void main (string [] ARGs)
{
// Set the Server IP Address
IPaddress IP = IPaddress. parse ("127.0.0.1 ");
Socket clientsocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Try
{
Clientsocket. Connect (New ipendpoint (IP, 8885); // Configure the server IP address and port
Console. writeline ("successfully connected to the server ");
}
Catch
{
Console. writeline ("failed to connect to the server. Press enter to exit! ");
Return;
}
// Receive data through clientsocket
Int incluelength = clientsocket. Receive (result );
Console. writeline ("received Server Message: {0}", encoding. ASCII. getstring (result, 0, cancelength ));
// Send data through clientsocket
For (INT I = 0; I <10; I ++)
{
Try
{
Thread. Sleep (1000); // wait 1 second
String sendmessage = "client send message hellp" + datetime. now;
Clientsocket. Send (encoding. ASCII. getbytes (sendmessage ));
Console. writeline ("send message to server: {0}" + sendmessage );
}
Catch
{
Clientsocket. Shutdown (socketshutdown. Both );
Clientsocket. Close ();
Break;
}
}
Console. writeline ("sent, press enter to exit ");
Console. Readline ();
}
}
}

 

After the compilation is successful, run the server and then the client to achieve the communication effect.

The effect is as follows:

The program has passed the LAN test. (192.168.x.x)

If compilation fails, you can download the project file at the following address:

Http://files.cnblogs.com/andrew-blog/SocketServerAndClient.rar

Http://www.cnblogs.com/andrew-blog/archive/2011/12/02/CSharp_Socket.html

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.