Simple TCP/IP Echo Server & Client Application in C#

简介: 1. TCP Server   The server’s job is to set up an endpoint for clients to connect to and passively wait for connections.

1. TCP Server

 

The server’s job is to set up an endpoint for clients to connect to and passively wait for connections.

The typical TCP server goes through two steps:

1. Construct a TcpListener instance, specifying the local address and port, and call the Start() method.

This socket listens for incoming connections on the specified port.

2. Repeatedly:
■ Call the AcceptTcpClient() method of TcpListener to get the next incoming
   client connection. Upon establishment of a new client connection, an instance of
   TcpClient for the new connection is created and returned by the AcceptTcp-
   Client() call.
■ Communicate with the client using the Read() and Write() methods of TcpClient’s
   NetworkStream.
■ Close the new client socket connection and stream using the Close() methods of
   NetworkStream and TcpClient.

TcpEchoServer.cs

using System; // For Console, Int32, ArgumentException, Environment
using System.Net; // For IPAddress
using System.Net.Sockets; // For TcpListener, TcpClient

class TcpEchoServer 
{
    private const int BUFSIZE = 32; // Size of receive buffer
    
    static void Main(string[] args) 
    {
        if (args.Length > 1) // Test for correct # of args
            throw new ArgumentException("Parameters: [<Port>]");
        
        int servPort = (args.Length == 1) ? Int32.Parse(args[0]): 7;

        TcpListener listener = null;

        try 
        {
            // Create a TCPListener to accept client connections
            listener = new TcpListener(IPAddress.Any, servPort);
            listener.Start();
        } 
        catch (SocketException se) 
        {
            Console.WriteLine(se.ErrorCode + ": " + se.Message);
            Environment.Exit(se.ErrorCode);
        }

        byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
        int bytesRcvd; // Received byte count

        for (;;) 
        { 
            // Run forever, accepting and servicing connections
            TcpClient client = null;
            NetworkStream netStream = null;
            try 
            {
                client = listener.AcceptTcpClient(); // Get client connection
                netStream = client.GetStream();
                Console.Write("Handling client - ");

                // Receive until client closes connection, indicated by 0 return value
                int totalBytesEchoed = 0;
                while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) 
                {
                    netStream.Write(rcvBuffer, 0, bytesRcvd);
                    totalBytesEchoed += bytesRcvd;
                }
                Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);

                // Close the stream and socket. We are done with this client!
                netStream.Close();
                client.Close();
            } 
            catch (Exception e) 
            {
                Console.WriteLine(e.Message);
                netStream.Close();
            }
        }
    }
}

The TcpListener listens for client connection requests on the port specified in the constructor.

Be careful to use a port that is not in use by another application, or a SocketException will be thrown.

Loop forever, iteratively handling incoming connections.

Receive and repeat data until the client closes.

Close the client stream and socket.

 

TcpEchoClient.cs

using System; // For String, Int32, Console, ArgumentException
using System.Text; // For Encoding
using System.IO; // For IOException
using System.Net.Sockets; // For TcpClient, NetworkStream, SocketException

class TcpEchoClient 
{
    static void Main(string[] args) 
    {
        if ((args.Length < 2) || (args.Length > 3)) 
        { 
            // Test for correct # of args
            throw new ArgumentException("Parameters: <Server> <Word> [<Port>]");
        }
        
        String server = args[0]; // Server name or IP address

        // Convert input String to bytes
        byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]);

        // Use port argument if supplied, otherwise default to 7
        int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;

        TcpClient client = null;
        NetworkStream netStream = null;

        try 
        {
            // Create socket that is connected to server on specified port
            client = new TcpClient(server, servPort);
            Console.WriteLine("Connected to server... sending echo string");
            netStream = client.GetStream();

            // Send the encoded string to the server
            netStream.Write(byteBuffer, 0, byteBuffer.Length);
            Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
            int totalBytesRcvd = 0; // Total bytes received so far
            int bytesRcvd = 0; // Bytes received in last read

            // Receive the same string back from the server
            while (totalBytesRcvd < byteBuffer.Length) 
            {
                if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0) 
                {
                    Console.WriteLine("Connection closed prematurely.");
                    break;
                }
                totalBytesRcvd += bytesRcvd;
            }
            Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
            Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
        } 
        catch (Exception e) 
        {
            Console.WriteLine(e.Message);
        } 
        finally 
        {
            netStream.Close();
            client.Close();
        }
    }
}

 

目录
相关文章
|
15天前
|
开发框架 缓存 .NET
C# 一分钟浅谈:Blazor Server 端开发
Blazor Server 是基于 ASP.NET Core 的框架,允许使用 C# 和 Razor 语法构建交互式 Web 应用。本文介绍 Blazor Server 的基本概念、快速入门、常见问题及解决方案,帮助开发者快速上手。涵盖创建应用、基本组件、数据绑定、状态管理、跨组件通信、错误处理和性能优化等内容。
29 1
|
16天前
|
缓存 C# 开发者
C# 一分钟浅谈:Blazor Server 端开发
本文介绍了 Blazor Server,一种基于 .NET 的 Web 开发模型,允许使用 C# 和 Razor 语法构建交互式 Web 应用。文章从基础概念、创建应用、常见问题及解决方案、易错点及避免方法等方面详细讲解,帮助开发者快速上手并提高开发效率。
39 2
|
4月前
|
Linux C#
【Azure App Service】C#下制作的网站,所有网页本地测试运行无误,发布至Azure之后,包含CHART(图表)的网页打开报错,错误消息为 Runtime Error: Server Error in '/' Application
【Azure App Service】C#下制作的网站,所有网页本地测试运行无误,发布至Azure之后,包含CHART(图表)的网页打开报错,错误消息为 Runtime Error: Server Error in '/' Application
|
网络协议
TCP client
TCP client
90 0
|
网络协议 Linux 测试技术
我个人的Linux TCP server和client测试源码,C语言(2)(★firecat推荐★)
我个人的Linux TCP server和client测试源码,C语言(2)(★firecat推荐★)
350 0
我个人的Linux TCP server和client测试源码,C语言(2)(★firecat推荐★)
|
网络协议 Linux C语言
我个人的Linux TCP server和client测试源码,C语言(2)(★firecat推荐★)
我个人的Linux TCP server和client测试源码,C语言(2)(★firecat推荐★)
177 0
|
负载均衡 网络协议 Linux
我个人的Linux TCP server和client测试源码,C语言(3)(★firecat推荐★)
我个人的Linux TCP server和client测试源码,C语言(3)(★firecat推荐★)
298 0
|
网络协议 NoSQL Linux
我个人的Linux TCP server和client测试源码,C语言(1)(★firecat推荐★)
我个人的Linux TCP server和client测试源码,C语言(1)(★firecat推荐★)
243 0
|
网络协议
ETCD Client 的生命周期影响系统TCP连接资源
最近发现一个 ETCD Client 端的实现问题——ETCD 所在机器宕机或者断网的情况下,ETCD Client 无法快速重连到可用的 etcd 节点,导致 client 端不可用(该问题的描述后续发表文章介绍)。
7833 0
|
网络协议 关系型数据库 Linux
PostgreSQL pgsocket: Extension for Simple TCP/IP Socket Client
标签 PostgreSQL , pgsocket 背景 PostgreSQL 插件,向外部tpc/ip socket服务发生字节流。 pgsocket is an extension for PostgreSQL server to send bytes to remote TCP/IP socket server.
859 0