asp.net C # Socket server and client communication implementation code

Source: Internet
Author: User
Tags readline socket

The first service-side (Server) complete code is as follows:


Introduction of namespaces:

The code is as follows Copy Code

Using System.Net.Sockets;
Using System.Net;
Using System.Threading;

The complete code is as follows:

The code is as follows Copy Code
Namespace Socketserver
{
Class Program
{
private static byte[] result = new byte[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)); Binding IP Address: port
Serversocket.listen (10); Set up to 10 queued connection requests
Console.WriteLine ("Start listening {0} successful", serverSocket.LocalEndPoint.ToString ());
Sending data through Clientsoket
Thread mythread = new Thread (listenclientconnect);
Mythread.start ();
Console.ReadLine ();
}

<summary>
Listening for client connections
</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 Message
</summary>
<param name= "Clientsocket" ></param>
private static void ReceiveMessage (object clientsocket)
{
Socket Myclientsocket = (socket) Clientsocket;
while (true)
{
Try
{
Receiving data through Clientsocket
int receivenumber = myclientsocket.receive (result);
Console.WriteLine ("Receive 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 for the server end.

The complete code for the client (clients) is as follows:

Introduction of namespaces:

The code is as follows Copy Code

Using System.Net;
Using System.Net.Sockets;
Using System.Threading;

Complete code:

The code is as follows Copy Code

Namespace Socketclient
{
Class Program
{
private static byte[] result = new byte[1024];
static void Main (string[] args)
{
Set 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 server IP and port
Console.WriteLine ("Connect server succeeded");
}
Catch
{
Console.WriteLine ("Failed to connect to the server, please press ENTER to exit!") ");
Return
}
Receiving data through Clientsocket
int receivelength = clientsocket.receive (result);
Console.WriteLine ("Receive Server message: {0}", Encoding.ASCII.GetString (Result,0,receivelength));
Sending data through Clientsocket
for (int i = 0; i < i++)
{
Try
{
Thread.Sleep (1000); Wait 1 seconds.
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 ("Send finished, press ENTER to exit");
Console.ReadLine ();
}
}
}

Once the compilation succeeds, the server is run, and the client is run to achieve the communication effect.

Click to download source file: Http://www.111cn.net/down/SocketServerAndClient.rar

Related Article

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.