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 = ; // Size of receive buffer static void Main(string[] args)
{
if (args.Length > ) // Test for correct # of args
throw new ArgumentException("Parameters: [<Port>]"); int servPort = (args.Length == ) ? Int32.Parse(args[]): ; 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 = ;
while ((bytesRcvd = netStream.Read(rcvBuffer, , rcvBuffer.Length)) > )
{
netStream.Write(rcvBuffer, , 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 < ) || (args.Length > ))
{
// Test for correct # of args
throw new ArgumentException("Parameters: <Server> <Word> [<Port>]");
} String server = args[]; // Server name or IP address // Convert input String to bytes
byte[] byteBuffer = Encoding.ASCII.GetBytes(args[]); // Use port argument if supplied, otherwise default to 7
int servPort = (args.Length == ) ? Int32.Parse(args[]) : ; 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, , byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = ; // Total bytes received so far
int bytesRcvd = ; // 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)) == )
{
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer, , totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
netStream.Close();
client.Close();
}
}
}

Simple TCP/IP Echo Server & Client Application in C#的更多相关文章

  1. netty写Echo Server & Client完整步骤教程(图文)

    1.创建Maven工程 1.1 父节点的pom.xml代码(root pom文件) 1 <?xml version="1.0" encoding="UTF-8&qu ...

  2. 流媒体 8——因特网 tcp/ip

    1 因特网 1.1 因特网的结构 组成因特网的子网之间在物理上的相互连接都是通过网关设备实现的.通过网关设备互相连接在一起的不同的网络通常称为子网 (subnetwork),因为它们是大网络之中的网络 ...

  3. 【TCP/IP 合约】 TCP/IP 基金会

    总结 : 通过学习 TCP/IP 基础, 并总结相关笔记 和 绘制思维导图 到博客上, 对 TCP/IP 框架有了大致了解, 之后開始详细学习数据链路层的各种细节协议, 并作出笔记; 博客地址 : h ...

  4. OSI七层模型和tcp/ip四层模型对比

    OSI 与TCP/IP 模型对比 OSI 协议层名称 TCP/IP 协议层名称 封装的单元 功能描述 TCP/IP协议 应用层(Application) 应用层(Application) 数据 应用程 ...

  5. [心平气和读经典]The TCP/IP Guide(000)

    The TCP/IP Guide [Page 39] The TCP/IP Guide: Introduction and "Guide to The Guide" | 第1章 概 ...

  6. 计算机网络历史与基本概念&分层与参考模型(TCP/IP与OSI)&通信过程

    Definition: 计算机网络:使用单一技术相互连接的自主计算机的互联集合. 单台计算机独立自主(不受制于其他计算机),连接介质可以使光纤.铜线也可以是微波.红外.卫星. 互联网络(Interne ...

  7. com.microsoft.sqlserver.jdbc.SQLServerException: 通过端口 1433 连接到主机 127.0.0.1 的 TCP/IP 连接失败。错误:“Connection refused: connect。请验证连接属性。确保 SQL Server 的实例正在主机上运行,且在此端口接受 TCP/IP 连接,还要确保防火墙没有阻止到此端口的 TCP 连接。”

    检查SQL Server Configuration Manager 确定实例名为"SKYSQLEXPRESS"下的TCP/IP已经开启了: sql2014配置(系统为Window ...

  8. SQL Server 连接问题-TCP/IP

    原文:SQL Server 连接问题-TCP/IP 出自:http://blogs.msdn.com/b/apgcdsd/archive/2012/02/24/ms-sql-server-tcp-ip ...

  9. service structure flowchart [mobile to server via HTTP RESTful API and TCP/IP in a map]

    mobile to server in RESTful and TCP/IP way

随机推荐

  1. TCP/IP——IP网络协议简记

    IP提供不可靠.无连接的数据报传送服务 不可靠:不保证IP数据报能成功到达目的地,当发生错误时,IP的做法是丢弃这个数据报,然后发送ICMP消息报给信息源. 无连接:IP不维护任何关于后续数据报的状态 ...

  2. 【SQL】176. Second Highest Salary

    Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S ...

  3. OpenGL的一些重要函数记录

    glViewport - set the viewport https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glViewport.x ...

  4. Redis_常用5大数据类型简介

    前面介绍了一些redis的的基本配置,以及安装,本文继续学习redis的五大数据类型. 一.Redis的五大数据类型 String(字符串).List(列表).Set(集合).Hash(哈希,类似ja ...

  5. 扩展gcd codevs 1213 解的个数

    codevs 1213 解的个数  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题目描述 Description 已知整数x,y满足如下面的条件: ax+by ...

  6. VK Cup 2016 - Round 1 (Div. 2 Edition) E. Bear and Contribution 单调队列

    E. Bear and Contribution 题目连接: http://www.codeforces.com/contest/658/problem/E Description Codeforce ...

  7. zoj 1610 Count the Colors 线段树区间更新/暴力

    Count the Colors Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://acm.zju.edu.cn/onlinejudge/show ...

  8. 如何在Ubuntu中用firefox浏览器查看chm文档?

    首先下载这插 件:在firefox中点击“工具”->“附加软件”->“扩展”,在firefix扩展网页下搜索“"chmfox" 然后安装,重启后就可以了.

  9. HDU 4691 Front compression (2013多校9 1006题 后缀数组)

    Front compression Time Limit: 5000/5000 MS (Java/Others)    Memory Limit: 102400/102400 K (Java/Othe ...

  10. Delphi CompilerVersion Constant / Compiler Conditional Defines

    http://delphi.wikia.com/wiki/CompilerVersion_Constant The CompilerVersion constant identifies the in ...