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.
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#的更多相关文章
- netty写Echo Server & Client完整步骤教程(图文)
1.创建Maven工程 1.1 父节点的pom.xml代码(root pom文件) 1 <?xml version="1.0" encoding="UTF-8&qu ...
- 流媒体 8——因特网 tcp/ip
1 因特网 1.1 因特网的结构 组成因特网的子网之间在物理上的相互连接都是通过网关设备实现的.通过网关设备互相连接在一起的不同的网络通常称为子网 (subnetwork),因为它们是大网络之中的网络 ...
- 【TCP/IP 合约】 TCP/IP 基金会
总结 : 通过学习 TCP/IP 基础, 并总结相关笔记 和 绘制思维导图 到博客上, 对 TCP/IP 框架有了大致了解, 之后開始详细学习数据链路层的各种细节协议, 并作出笔记; 博客地址 : h ...
- OSI七层模型和tcp/ip四层模型对比
OSI 与TCP/IP 模型对比 OSI 协议层名称 TCP/IP 协议层名称 封装的单元 功能描述 TCP/IP协议 应用层(Application) 应用层(Application) 数据 应用程 ...
- [心平气和读经典]The TCP/IP Guide(000)
The TCP/IP Guide [Page 39] The TCP/IP Guide: Introduction and "Guide to The Guide" | 第1章 概 ...
- 计算机网络历史与基本概念&分层与参考模型(TCP/IP与OSI)&通信过程
Definition: 计算机网络:使用单一技术相互连接的自主计算机的互联集合. 单台计算机独立自主(不受制于其他计算机),连接介质可以使光纤.铜线也可以是微波.红外.卫星. 互联网络(Interne ...
- 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 ...
- SQL Server 连接问题-TCP/IP
原文:SQL Server 连接问题-TCP/IP 出自:http://blogs.msdn.com/b/apgcdsd/archive/2012/02/24/ms-sql-server-tcp-ip ...
- 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
随机推荐
- Eclipse酷炫项目、最新趋势介绍
作为Eclipse基金组织的执行董事,我需要经常审阅每一个新提交的Eclipse项目协议书.作为Eclipse的一分子,我很乐意与加入我们团队的新开发人员互动.这也是我工作中的乐趣之一.2013年,我 ...
- 【BZOJ 2982】 2982: combination (卢卡斯定理)
2982: combination Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 510 Solved: 316 Description LMZ有n个 ...
- hdu 1011 树形dp+背包
题意:有n个房间结构可看成一棵树,有m个士兵,从1号房间开始让士兵向相邻的房间出发,每个房间有一定的敌人,每个士兵可以对抗20个敌人,士兵在某个房间对抗敌人使无法走开,同时有一个价值,问你花费这m个士 ...
- Problem A: 深入浅出学算法002-n个1
Description 由n个1组成的整数能被K(K<10000)整除,n至少为多少? Input 多组测试数据,第一行输入整数T,表示组数 然后是T行,每行输入1个整数代表K Output 对 ...
- bzoj 1026
很久以前做过的一道数位DP,现在用一种新的解决数位DP的比较一般的方法. 数位DP裸题是:求[L,R]有多少个数. 先转化成求[0,R]有多少个数,然后区间相减即可. 对于[0,R]中的所有数,用0补 ...
- 为什么java的构造方法中this()或者super()要放在第一行
java的构造方法中如果自己显性的调用super()的时候一定要放在第一行,如不是的话就会报错. 为什么一定要在第一行? super()在第一行的原因就是: 子类有可能访问了父类对象, 比如在构造函数 ...
- 设计模式 - 观察者模式(Observer Pattern) Java内置 用法
观察者模式(Observer Pattern) Java内置 用法 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26601659 ...
- UVA1493 - Draw a Mess(并查集)
UVA1493 - Draw a Mess(并查集) 题目链接 题目大意:一个N * M 的矩阵,每次你在上面将某个范围上色,不论上面有什么颜色都会被最新的颜色覆盖,颜色是1-9,初始的颜色是0.最后 ...
- java内存泄露补充样例
前几天写了个内存泄露的文章.里面介绍了内存泄露的相关知识:http://blog.csdn.net/u010590685/article/details/46973735 但是里面给的样例不是非常好, ...
- 怎样用git提交多次改动
在提交完代码后,我们发现所改动的文件还有须要完好的地方,可是我们已经upload过了可是还未合入到库上,此时要提交新的改动有两种做法: 一是等上次的改动合入到库上后,再次upload提交一次,这明显是 ...