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. 【SQL】175. Combine Two Tables

    Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ | PersonId ...

  2. bound和unbound方法,类的绑定和非绑定是什么

    作者:灵剑链接:https://www.zhihu.com/question/41006598/answer/148994582来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  3. 【欧拉函数】BZOJ4173-数学

    [题目大意] [思路] 基本是popoqqq大爷的题解,稍微添加了几句自己的注释,方便理解 同理,如果n%k+m%k<k等价于0 =∑([(n+m)/k]-[n/k]-[m/k])×φ(k) … ...

  4. HTML && xml 的区别

    HTML && xml 的区别 HTML 超文本标记语言 xml 可扩展标记语言 jsp  表面是一个HTML页面,本质是一个servlet HTML  超文本标记语言 HTML 是一 ...

  5. Problem E: 深入浅出学算法006-求不定方程的所有解

    Description 现有一方程ax+by=c,其中系数a.b.c均为整数,求符合条件的所有正整数解,要求按x由小到大排列,其中a b c 均为不大于1000的正整数 Input 多组测试数据,第一 ...

  6. bzoj 1715: [Usaco2006 Dec]Wormholes 虫洞 -- spfa判断负环

    1715: [Usaco2006 Dec]Wormholes 虫洞 Time Limit: 5 Sec  Memory Limit: 64 MB 注意第一次加边是双向边第二次是单向边,并且每次询问前数 ...

  7. Codeforces Beta Round #9 (Div. 2 Only) B. Running Student 水题

    B. Running Student 题目连接: http://www.codeforces.com/contest/9/problem/B Description And again a misfo ...

  8. April Fools Day Contest 2016 G. You're a Professional

    G. You're a Professional 题目连接: http://www.codeforces.com/contest/656/problem/G Description A simple ...

  9. java类中元素初始化顺序详解

    父类静态变量父类静态块子类静态变量子类静态块父类普通变量父类普通块父类构造方法子类普通变量子类普通块子类构造方法

  10. 阻止a标签跳转

       一.在html中 1. <a href="javascript:;"></a> 2. <a href="###">&l ...