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
随机推荐
- JMS 基本可靠性机制 和 事务机制
4.3.1 基本可靠性机制4.3.1.1 控制消息的签收(Acknowledgment) 客户端成功接收一条消息的标志是这条消息被签收.成功接收一条消息一般包括如 下三个阶段:1.客户端接收消息:2. ...
- POJ3450 Corporate Identity
后缀数组. 解决多个字符串的最长公共子串. 采用对长度的二分,将子串按height分组,每次判断是否在每个字符串中都出现过. 复杂度O(NlogN) By:大奕哥 #include<cstrin ...
- BZOJ1935 园丁的烦恼
一个二维偏序的问题,学过了三维偏序cdq分治之后觉得这个题非常的水.只需按一维排序之后再用树状数组操作即可.——by VANE #include<bits/stdc++.h> using ...
- hibernate之条件查询
一.条件查询简介 条件查询是更据面向对象特色的数据查询方式,主要通过如下3个类完成 1.Criteria:代表一次查询 2.Criterion:代表一个查询条件 3.Restrictions:产生查询 ...
- Java并发(十一):Condition条件
先做总结: 1.为什么使用Condition条件? synchronized配合Object的wait().notify()系列方法可以实现等待/通知模式. Lock提供了条件Condition,对线 ...
- 对Java Serializable(序列化)的理解和总结(二)
遇到这个 Java Serializable 序列化这个接口,我们可能会有如下的问题a,什么叫序列化和反序列化 b,作用.为啥要实现这个 Serializable 接口,也就是为啥要序列化 c,ser ...
- 解决XP系统访问Win10打印机被拒绝的问题
打印机是办公室人员经常会用到的设备,为了方便多人使用都会将打印机设置共享,可是会有许多xp系统用户需要访问win10系统上的打印机,这时候却发现拒绝访问无法连接,该如何解决呢? 其实这是win10做的 ...
- Bellman-ford 算法详解
昨天说的dijkstra固然很好用,但是却解决不了负权边,想要解决这个问题,就要用到Bellman-ford. 我个人认为Bellman-Ford比dijkstra要好理解一些,还是先上数据(有向图) ...
- 一个简单RPC框架是怎样炼成的(V)——引入传输层
开局篇我们说了,RPC框架的四个核心内容 RPC数据的传输. RPC消息 协议 RPC服务注冊 RPC消息处理 接下来处理传输数据.实际应用场景一般都是基于socket.socket代码比較多, ...
- Current-sense monitor and MOSFET boost output current
A previous Design Idea describes a programmable current source that used a three-terminal National S ...