C # (socket) Synchronous Socket code Sample _c# Tutorial

Source: Internet
Author: User
Tags string back
Synchronizing client Sockets sample

The following example program creates a client that is connected to the server. The client is generated with a synchronous socket, so the execution of the client application is suspended until the server returns a response. The application sends a string to the server and then displays the string returned by the server in the console.

C#
Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
public class Synchronoussocketclient {
public static void Startclient () {
Data buffer for incoming data.
byte[] bytes = new byte[1024];
Connect to a remote device.
try {
Establish the remote endpoint for the socket.
This is example uses port 11000 on the local computer.
Iphostentry iphostinfo = Dns.resolve (Dns.gethostname ())
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint remoteep = new IPEndPoint (ipaddress,11000);
Create a TCP/IP socket.
Socket sender = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, PROTOCOLTYPE.TCP);
Connect the socket to the remote endpoint. Catch any errors.
try {
Sender. Connect (remoteEP);
Console.WriteLine ("Socket connected to {0}",
Sender. Remoteendpoint.tostring ());
Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes ("This is a test<eof>");
Send the data through the socket.
int bytessent = sender. Send (msg);
Receive the response from the remote device.
int Bytesrec = sender. Receive (bytes);
Console.WriteLine ("echoed Test = {0}",
Encoding.ASCII.GetString (Bytes,0,bytesrec));
Release the socket.
Sender. Shutdown (Socketshutdown.both);
Sender. Close ();
catch (ArgumentNullException ane) {
Console.WriteLine ("ArgumentNullException: {0}", ane.) ToString ());
catch (SocketException se) {
Console.WriteLine ("SocketException: {0}", se.) ToString ());
catch (Exception e) {
Console.WriteLine ("Unexpected exception: {0}", e.tostring ());
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
public static int Main (string[] args) {
Startclient ();
return 0;
}
}
Synchronization Server Socket Example The following example program creates a server that receives a connection request from a client. The server is generated with a synchronous socket.
Therefore, the execution of the server application is suspended while waiting for a connection from the client. The application receives a string from the client,
Display the string in the console, and then echo the string back to the client. The string from the client must contain the string "<EOF>".
To emit a signal that indicates the end of the message.








C#
Copy Code

Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
public class Synchronoussocketlistener {
Incoming data from the client.
public static string data = NULL;
public static void Startlistening () {
Data buffer for incoming data.
byte[] bytes = new byte[1024];
Establish the local endpoint for the socket.
Dns.gethostname returns the name of the
Host running the application.
Iphostentry iphostinfo = Dns.resolve (Dns.gethostname ());
IPAddress ipaddress = iphostinfo.addresslist[0];
IPEndPoint localendpoint = new IPEndPoint (ipaddress, 11000);
Create a TCP/IP socket.
Socket listener = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, PROTOCOLTYPE.TCP);
Bind the socket to the local endpoint and
Listen for incoming connections.
try {
Listener. Bind (Localendpoint);
Listener. Listen (10);
Start listening for connections.
while (true) {
Console.WriteLine ("Waiting for a Connection ...");
Program was suspended while waiting for a incoming connection.
Socket handler = listener. Accept ();
data = null;
An incoming connection needs is processed.
while (true) {
bytes = new byte[1024];
int Bytesrec = handler. Receive (bytes);
Data + + Encoding.ASCII.GetString (BYTES,0,BYTESREC);
if (data. IndexOf ("<EOF>") >-1) {
Break
}
}
Show the data on the console.
Console.WriteLine ("Text Received: {0}", data);
Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes (data);
Handler. Send (msg);
Handler. Shutdown (Socketshutdown.both);
Handler. Close ();
}
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
Console.WriteLine ("\npress ENTER to continue ...");
Console.read ();
}
public static int Main (string[] args) {
Startlistening ();
return 0;
}
}

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.