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();
}
}
}

最新文章

  1. MySQL 优化MySQL Server
  2. X-Cart 学习笔记 完整目录
  3. git-tag
  4. GIT安装完需要做以下配置
  5. 解决TextView最后一行显示不全
  6. semat内核阿尔法的状态图
  7. hadoop 蓄水池抽样 分布式抽样
  8. mac tree命令
  9. jsp servelet
  10. c# List集合排序
  11. document.createElement()的用法
  12. NHibernate各种数据库连接参数文件配置方法说明
  13. 第10课_dg
  14. HDU 4726 Kia&#39;s Calculation (贪心算法)
  15. 数据库中File权限的危害
  16. [Swift]LeetCode286. 墙和门 $ Walls and Gates
  17. python之字符编码
  18. 最近公共祖先 LCA 倍增算法
  19. appium --log-timestamp &gt; appium.log
  20. 从零开始学习VoltDB

热门文章

  1. 打开tcp_tw_recycle引起的一个问题
  2. 基于python中staticmethod和classmethod的区别(详解)
  3. Scrapy实战篇(七)之Scrapy配合Selenium爬取京东商城信息(下)
  4. 初始Hibernate4
  5. 【BZOJ 4305】 4305: 数列的GCD (数论)
  6. [NOI2007]货币兑换 --- DP + 斜率优化(CDQ分治)
  7. 【费用流】BZOJ1927-[Sdoi2010]星际竞速
  8. 通过wifi上网,桥接模式下virtualBox虚拟机无法连上网的解决办法
  9. [转]android中listview点击事件失效
  10. python string和dict转换