C # example of sending and receiving through SOCKET,
Socket Client
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Net;
Using System. Net. Sockets;
Namespace A0140_SocketClient.Sample
{
/// <Summary>
/// This class is an example of a Socket Client.
/// This class simply connects to the Socket server and sends a message.
/// Then read the feedback from the server
/// End the program.
///
/// Server output:
/// Start listening on port 8088 ......
/// Receive the customer's connection
/// The received data from the client is Hello Socket Server!
///
/// Client output:
/// Sent to the Server: Hello Socket Server!
/// Received from the Server: Hello Socket Server!
///
/// </Summary>
Class StockClient
{
/// <Summary>
/// Character encoding.
/// </Summary>
Private static readonly Encoding ASCII;
/// <Summary>
/// The port used for sending/receiving.
/// </Summary>
Private const int PORT = 8088;
Private const String SEND_MESSAGE = "Hello Socket Server! ";
Static StockClient ()
{
ASCII = Encoding. ASCII;
}
Public void SendMessage ()
{
// Construct the byte buffer for sending.
Byte [] sendBytes = ASCII. GetBytes (SEND_MESSAGE );
// Construct the byte buffer for receiving.
Byte [] recvBytes = new Byte [1, 256];
// Ip address.
IPAddress localAddr = IPAddress. Parse ("127.0.0.1 ");
// Access point.
IPEndPoint ephost = new IPEndPoint (localAddr, PORT );
// The first parameter: AddressFamily = specifies the addressing scheme that can be used by the Socket class instance.
// Unspecified: The address family is not specified.
// Address of InterNetwork IP version 4.
// InterNetworkV6 IP address 6.
//
// The second parameter: SocketType = specifies the Socket type represented by the Socket class instance.
// Stream is a socket type that supports reliable, bidirectional, and connection-based byte streams without repeating data or retaining boundaries.
// This type of Socket communicates with a single host and requires a remote host connection before the communication starts.
// This socket type uses the Transmission Control Protocol (Tcp). AddressFamily can be InterNetwork or InterNetworkV6.
//
// The third parameter: ProtocolType = specifies the protocol supported by the Socket class.
// Tcp transmission control protocol (TCP ).
Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Try
{
// Try to connect to the host.
S. Connect (ephost );
Console. WriteLine ("sent to server: {0}", SEND_MESSAGE );
// Send data to the host.
S. Send (sendBytes, sendBytes. Length, SocketFlags. None );
// Receives the server response.
Int32 bytes = s. Receive (recvBytes, recvBytes. Length, SocketFlags. None );
StringBuilder buff = new StringBuilder ();
While (bytes> 0)
{
// Replace the buffered byte array with a string.
String str = ASCII. GetString (recvBytes, 0, bytes );
// Add String cache
Buff. Append (str );
// Accept it again and check whether there is any data later.
Bytes = s. Receive (recvBytes, recvBytes. Length, SocketFlags. None );
}
Console. WriteLine ("received from server: {0}", buff. ToString ());
}
Catch (Exception ex)
{
Console. WriteLine ("An error occurred while connecting, sending, and receiving! ");
Console. WriteLine (ex. Message );
Console. WriteLine (ex. StackTrace );
}
Finally
{
S. Close ();
}
}
}
}
Socket server
Using System;
Using System. IO;
Using System. Net;
Using System. Net. Sockets;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
Namespace A0130_SocketServer.Sample
{
/// <Summary>
/// Socket server example
///
/// This example only processes Access from one client and exits after processing.
///
///
/// The server output is:
///
/// Start listening on port 8088 ......
/// Receive the customer's connection
/// The received data from the client is: 1
///
///
///
/// The client input is:
///
/// Telnet 127.0.0.1 8088
/// 1
/// The connection to the host is lost.
///
///
/// </Summary>
Class SocketServer
{
/// <Summary>
/// Character encoding.
/// </Summary>
Private static readonly Encoding ASCII;
/// <Summary>
/// The port used for listening.
/// </Summary>
Private const int PORT = 8088;
Static SocketServer ()
{
ASCII = Encoding. ASCII;
}
Public void StartServer ()
{
TcpListener myListener = null;
Try
{
// Ip address.
IPAddress localAddr = IPAddress. Parse ("127.0.0.1 ");
// Enable a listener on port 8088.
MyListener = new TcpListener (localAddr, PORT );
// Start listening.
MyListener. Start ();
Console. WriteLine ("Start listening on port {0 ...... ", PORT );
// The program is paused here, waiting for access from the client.
Socket mySocket = myListener. AcceptSocket ();
// If the command is executed here, the client's connection is received.
Console. WriteLine ("received client connection ");
// Byte buffer.
Byte [] recvBytes = new Byte [1, 256];
// Read data to the buffer
Int32 bytes = mySocket. Receive (recvBytes, recvBytes. Length, SocketFlags. None );
// Convert the byte array in the buffer to a string.
String str = ASCII. GetString (recvBytes, 0, bytes );
Console. WriteLine ("received data from the client: {0}", str );
// Send the read data back to the client.
MySocket. Send (recvBytes, bytes, SocketFlags. None );
// Sleep for 5 seconds.
Thread. Sleep (5000 );
// Close the Socket
MySocket. Close ();
}
Catch (SocketException e)
{
Console. WriteLine ("SocketException: {0}", e );
}
Finally
{
MyListener. Stop ();
}
}
}
}