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
随机推荐
- 「ZJOI2018」历史
「ZJOI2018」历史 前置知识 \(\text{LCT}\) 维护子树信息,考虑辅助树上一个节点的子树信息只是其代表的这一段链的信息,设 \(S(u)\) 为节点 \(u\) 的子树信息,那么在辅 ...
- luoguP3750 [六省联考2017]分手是祝愿 概率期望DP + 贪心
...........真的神状态了,没办法去想的状态................... 考试的时候选择$50$分贪心+$15$分状压吧,别的点就放弃算了........ 令$f[i]$表示从最小步 ...
- DP练习 巡逻
国庆这天五一大道上人头攒动,这是因为大家都准备从五一广场上那个大屏幕观看新中国60周年的国庆阅兵式!这虽然是一件很喜庆的事情,可却让CS市的警察局长伤透了脑筋的,因为人潮拥挤是很容易发生安全事故的. ...
- iOS Core Animation 动画 入门学习(一)基础
reference:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide ...
- linux常见命令集合(下)
1. tar zcvf backup-$(date "+%Y-%m-%d").tar.gz demo01dir 常用命令集合 echo helloworld date “+%y-% ...
- URAL 1995 Illegal spices 贪心构造
Illegal spices 题目连接: http://acm.timus.ru/problem.aspx?space=1&num=1995 Description Jabba: Han, m ...
- Educational Codeforces Round 10 C. Foe Pairs 水题
C. Foe Pairs 题目连接: http://www.codeforces.com/contest/652/problem/C Description You are given a permu ...
- 拉普拉斯(Laplace)分布
Laplace分布的概率密度函数的形式是这样的: $p(x) = \frac{1}{2 \lambda} e^{-\frac{\vert x –\mu \vert}{\lambda}}$ 一般$\ ...
- 如何解决…has been modified since the precompiled header… was built的问题
如何解决…has been modified since the precompiled header… was built 的问题 xcode5.1在程序中报错: File '/Applicatio ...
- ASM相关视图
oracle asm对于我们并非一个黑盒子 ,我们能够通过对应视图查看asm instance信息,和oracle系统视图一样. v$asm_diskgroup x$kfgrp 记录diskgrou ...