C# Source Code: TCP Client Server Demonstration using Sockets
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
TCP Client Server Demonstration using Sockets
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, January 12, 2005
Hits:
3940
Category:
Sockets/Internet/Remote Comms
Article:
Below is some source code demonstrating how to use the .NET Socket classes to create a simple TCP client/server console application: using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; namespace VBusers.Sockets.TCP { #region Test Class ///
/// Demonstration Test Class. ///
class TestClass { private static TcpEchoServer _tcpServer = null; ///
/// The main entry point for the application. ///
[STAThread] static void Main(string[] args) { // Start the TCP server listening for clients on a new thread Thread server = new Thread( new ThreadStart( StartServerThread ) ); server.Start(); Console.WriteLine( "Main: Starting TCP Server..."); do { // Wait for the server to start up Thread.Sleep( 100 ); } while (_tcpServer != null && !_tcpServer.Listening ); // Get the client to send a message to the server // and print the response string serverResponse = TcpEchoClient.SendAndGetData("TEST MESSAGE", "localhost", 7); _tcpServer.Dispose(); // Bring the server thread down // server.Abort(); Console.WriteLine( "Main: Press Any Key to Close... "); Console.ReadLine(); } ///
/// Starts the TCP server listening for clients. ///
static void StartServerThread() { _tcpServer = new TcpEchoServer(); _tcpServer.StartListening(); } } #endregion Test Class #region TCP Client ///
/// TCP client socket class. Sends messages to the specified TCP server. ///
///
For DEMONSTRATION ONLY. NOT SUITABLE FOR APPLICATION CODE!!!
class TcpEchoClient { ///
/// Sends data to a server and returns the servers reply. ///
///
The data to send to the server. ///
The server to send the message to. ///
The server port. ///
The reply from the server.
public static string SendAndGetData(string data, string serverName, int serverPort) { // Convert data into a byte array, byte[] byteBuffer = Encoding.ASCII.GetBytes( data ); string serverResponse = string.Empty; Socket sock = null; try { // Create a TCP socket instance sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Creates server IPEndPoint instance. We assume Resolve returns at least one address IPEndPoint serverEndPoint = new IPEndPoint(Dns.Resolve(serverName).AddressList[0], serverPort); // Connect the socket to server on specified port sock.Connect( serverEndPoint ); Console.WriteLine("Client: Connected to server '{0}'", serverName, data); Console.WriteLine("Client: Sending data '{1}'", serverName, data); // Send the encoded string to the server sock.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None); // Notify the server that the send stream has finished (server will read will return zero) sock.Shutdown( SocketShutdown.Send ); Console.WriteLine("Client: Successfully sent {0} bytes to server.", byteBuffer.Length); int byteCount = 0; int bytesReceived = 0; // Receive the same string back from the server do { if ((bytesReceived = sock.Receive(byteBuffer, byteCount, byteBuffer.Length - byteCount, SocketFlags.None)) == 0) { Console.WriteLine("Client: Finished reading server response."); break; } // Store byte count byteCount += bytesReceived; } while (true); serverResponse = Encoding.ASCII.GetString(byteBuffer, 0, byteCount); // Flush the buffers before closing the socket sock.Shutdown( SocketShutdown.Both ); Console.WriteLine("Client: Successfully received message '{0}' from server", serverResponse); } catch (Exception e) { // Handle errors Console.WriteLine("Client: " + e.Message); } finally { // Close connection sock.Close(); } return serverResponse; } } #endregion #region TCP Server ///
/// TCP Echo server class. Echos the data that a client sends it. ///
///
For DEMONSTRATION ONLY. NOT SUITABLE FOR APPLICATION CODE!!!
class TcpEchoServer: IDisposable { public int ServerPortNumber = 7; private Socket _serverSocket = null; private bool _listening = false; ///
/// Returns if the server is listening for client calls. ///
public bool Listening { get { return _listening; } } ///
/// Starts the TCP Server which listens for client connections ///
public void StartListening() { // Size of receive buffer const int BUFFER_SIZE = 6; // Number of outstanding connection queue max size const int CONNECTION_BACKLOG = 5; try { // Create a socket to accept client connections _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind to the port _serverSocket.Bind(new IPEndPoint(IPAddress.Any, ServerPortNumber)); // Start listening for a connections _serverSocket.Listen(CONNECTION_BACKLOG); } catch (SocketException ex) { // Handle errors Console.WriteLine("Server: " + ex.ErrorCode + ": " + ex.Message); return; } catch (Exception ex) { // Handle errors Console.WriteLine("Server: " + ex.ToString()); return; } byte[] incomingMessageBuffer = new byte[BUFFER_SIZE]; // Receive buffer int bytesReceived = 0; // Received byte count do { // Start loop to listen for clients Socket client = null; try { // Wait for a client connection _listening = true; client = _serverSocket.Accept(); // Display the client endpoint Console.WriteLine("Server: Received connection request from client at " + client.RemoteEndPoint ); // Receive until client calls ShutDown for SocketShutdown.Send (indicated by 0 return value) int byteCount = 0; while ((bytesReceived = client.Receive(incomingMessageBuffer, 0, incomingMessageBuffer.Length, SocketFlags.None)) > 0) { // Received data, send the data back to the client client.Send( incomingMessageBuffer, 0, bytesReceived, SocketFlags.None ); byteCount += bytesReceived; } Console.WriteLine("Server: Successfully sent {0} bytes back to client.", byteCount); // Flush the buffers before closing the socket client.Shutdown( SocketShutdown.Both ); // Close the socket client.Close(); } catch (Exception ex) { // Handle errors (will happen after Dispose is called) Console.WriteLine("Server Error (will be called after Dispose): " + ex.Message); if ( client != null && client.Connected ) { // Flush the buffers before closing the socket client.Shutdown( SocketShutdown.Both ); // Close the client client.Close(); } break; } } while (true); } #region IDisposable Members ///
/// Closes connection and frees resources ///
public void Dispose() { Console.WriteLine("Server: Closed Connection."); _listening = false; if ( _serverSocket != null ) { if ( _serverSocket.Connected ) { // Flush the buffers before closing the socket _serverSocket.Shutdown( SocketShutdown.Both ); // Close the socket _serverSocket.Close(); } _serverSocket = null; } } #endregion } #endregion }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet