C#简单的tcpserver
实现一个简单的TCPserver,用tcplistener实现。
当收到客户端特定信息"101"时,发送给客户端"202“指令。
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net; namespace TCPServerTutorial
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread; public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, );
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
Console.WriteLine("Server started at {0} :{1} @ {2}", IPAddress.Any, , DateTime.Now.ToString());
} private void ListenForClients()
{
this.tcpListener.Start(); while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient(); //create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
} private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
Console.WriteLine("Client @[{0}] connected @{1}", tcpClient.Client.LocalEndPoint,DateTime.Now.ToString()); NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[];
int bytesRead=;
//bool isRight=false; while (true)
{
bytesRead = ; try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, , );
}
catch
{
//a socket error has occured
Console.WriteLine("Error:receive msg error");
break;
} if (bytesRead == )
{
//the client has disconnected from the server
Console.WriteLine("Client @[{0}] disconnect @{1}", tcpClient.Client.LocalEndPoint,DateTime.Now.ToString());
break;
} //message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
//System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
string recvstr=encoder.GetString(message, , bytesRead);
Console.WriteLine("Recv:[{1}]:msg:@[{0}] @{2}", recvstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString()); //send msg to client
string sendstr = "Server OK";
if (recvstr=="")
{
//isRight = true;
sendstr = "";
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.White;
} byte[] buffer = encoder.GetBytes(sendstr);
clientStream.Write(buffer, , buffer.Length);
clientStream.Flush(); Console.WriteLine("Sent:[{1}]:msg:@[{0}] @{2}\r\n", sendstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());
} tcpClient.Close();
} } }
C#简单的tcpserver的更多相关文章
- Indy的TCPServer到底能支持多少个连接
最近一个项目,最开始使用IdTcpServer,在大压力测试的时候,只连接了800个多一点的客户端(每个客户端连接上之后每秒钟发送一个几十字节的报文,服务器应答).但是持续的时间不会超过10分钟,服务 ...
- Socket 由浅入深系列--------- 简单实现编程(三)
socket 由浅入深 原理(一)介绍了一些,以下也就是简单实现,并未考虑其它性能化! 使用TCP的server客户机举例 server 设置一个简单的TCPserver涉及下列步骤: 调用 sock ...
- Python使用TCPServer编写(多线程)Socket服务
SocketServer包对socket包进行了包装(封装),使得创建socket服务非常简单. TCPServer+BaseRequestHandler 使用TCPServer和BaseReques ...
- mina框架详解
转:http://blog.csdn.net/w13770269691/article/details/8614584 mina框架详解 分类: web2013-02-26 17:13 12651人 ...
- MINA2 框架详解(转)
Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP.UDP/IP协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务.虚拟机管道通信服务等),M ...
- 【转载】Python编写简易木马程序
转载来自: http://drops.wooyun.org/papers/4751?utm_source=tuicool 使用Python编写一个具有键盘记录.截屏以及通信功能的简易木马. 首先准备好 ...
- mina
http://bsr1983.iteye.com/blog/1886296 http://blog.csdn.net/defonds/article/category/1844073(这个网站原创最全 ...
- mina 通讯框架
Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP.UDP/IP协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务.虚拟机管道通信服务等),M ...
- Mina、Netty、Twisted一起学(七):公布/订阅(Publish/Subscribe)
消息传递有非常多种方式.请求/响应(Request/Reply)是最经常使用的.在前面的博文的样例中.非常多都是採用请求/响应的方式.当server接收到消息后,会马上write回写一条消息到clie ...
随机推荐
- 【甘道夫】HBase基本数据操作的详细说明【完整版,精绝】
介绍 之前具体写了一篇HBase过滤器的文章.今天把基础的表和数据相关操作补上. 本文档參考最新(截止2014年7月16日)的官方Ref Guide.Developer API编写. 全部代码均基于& ...
- 类 ArrayBlockingQueue<E>(一个由数组支持的有界阻塞队列。)
类型参数: E - 在此 collection 中保持的元素类型 所有已实现的接口: Serializable, Iterable<E>, Collection<E>, Blo ...
- eclipse中不能找到dubbo.xsd解决方法
使用dubbo时遇到问题: org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'htt ...
- Database and models
Database and models The database Now that we have the Album module set up with controller action met ...
- Oracle建表实例
建表一般来说是个挺简单的事情,但是Oracle的建表语句有很多可选的参数,有些我们可能平时不太用,用的时候又不知道怎么用,这里就写一个较完整的建表的例子: CREATE TABLE banping ...
- ajax的一部分知识
jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为String类型的参数,请求方式(p ...
- SpringMVC文件上传 Excle文件 Poi解析 验证 去重 并批量导入 MYSQL数据库
SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库 /** * 业务需求说明: * 1 批量导入成员 并且 自主创建账号 * 2 校验数据格式 且 重复导入提示 已被 ...
- C#学习笔记7:多态是面向对象的三大特征(封装、继承、多态)之一
多态: 多态是面向对象的三大特征(封装.继承.多态)之一. 什么是多态? 一个对象表现出多种状态. 多态的实现方法: 1.虚方法: 2.抽象方法: 3.接口. PS:New 关键词可以隐藏父类的方法. ...
- asp.net 中使用不同的数据源绑定gridview
第一种,使用SqlDataReader绑定gridview.代码如下: public SqlDataReader bind() { SqlConnection con = new SqlConnect ...
- ubuntu中安装monodevelop
sudo apt-get install monoDevelop sudo apt-get install build-essentialsudo apt-get install mono-devel ...