实现一个简单的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的更多相关文章

  1. Indy的TCPServer到底能支持多少个连接

    最近一个项目,最开始使用IdTcpServer,在大压力测试的时候,只连接了800个多一点的客户端(每个客户端连接上之后每秒钟发送一个几十字节的报文,服务器应答).但是持续的时间不会超过10分钟,服务 ...

  2. Socket 由浅入深系列--------- 简单实现编程(三)

    socket 由浅入深 原理(一)介绍了一些,以下也就是简单实现,并未考虑其它性能化! 使用TCP的server客户机举例 server 设置一个简单的TCPserver涉及下列步骤: 调用 sock ...

  3. Python使用TCPServer编写(多线程)Socket服务

    SocketServer包对socket包进行了包装(封装),使得创建socket服务非常简单. TCPServer+BaseRequestHandler 使用TCPServer和BaseReques ...

  4. mina框架详解

     转:http://blog.csdn.net/w13770269691/article/details/8614584 mina框架详解 分类: web2013-02-26 17:13 12651人 ...

  5. MINA2 框架详解(转)

    Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP.UDP/IP协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务.虚拟机管道通信服务等),M ...

  6. 【转载】Python编写简易木马程序

    转载来自: http://drops.wooyun.org/papers/4751?utm_source=tuicool 使用Python编写一个具有键盘记录.截屏以及通信功能的简易木马. 首先准备好 ...

  7. mina

    http://bsr1983.iteye.com/blog/1886296 http://blog.csdn.net/defonds/article/category/1844073(这个网站原创最全 ...

  8. mina 通讯框架

    Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP.UDP/IP协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务.虚拟机管道通信服务等),M ...

  9. Mina、Netty、Twisted一起学(七):公布/订阅(Publish/Subscribe)

    消息传递有非常多种方式.请求/响应(Request/Reply)是最经常使用的.在前面的博文的样例中.非常多都是採用请求/响应的方式.当server接收到消息后,会马上write回写一条消息到clie ...

随机推荐

  1. Java设计模式学习资源汇总

    本文记录了Java设计模式学习书籍.教程资源.此分享会持续更新: 1. 设计模式书籍 在豆瓣上搜索了一把,发现设计模式贯穿了人类生活的方方面面.还是回到Java与程序设计来吧. 打算先归类,再浏览,从 ...

  2. OC语言--NSFileManager& NSFileHandle

    1.关于文件的介绍 ->什么是文件: 文件概念, 广义文件. 狭义文件(磁盘文件). 文件常见的使用操作(可用命令行演示文件操作的使用场景). ->什么是路径: 简单来说就是,在系统中,要 ...

  3. 使用Zipalign工具优化Android APK应用记录

    生成的Android应用APK文件最好进行优化,因为APK包的本质是一个zip压缩文档,经过优化能使包内未压缩的数据有序的排列,从而减少应用程序运行时的内存消耗.我们可以使用Zipalign工具进行A ...

  4. 记 Ubuntu14.04 Monodevelop 安装的两个问题

    1. Monodevelop 不能执行,显示错误 The assembly mscorlib.dll was not found or could not be loaded. 首先要确定mono安装 ...

  5. 设计模式 - 命令模式(command pattern) 多命令 具体解释

    命令模式(command pattern) 多命令 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考命令模式: http://blog.csdn.ne ...

  6. EasyARM i.mx28学习笔记——开箱试用总结

    0 前言     本月初(2014年8月)购买了周立功的EasyARM开发板,主控为EasyARM i.mx287.出于下面几个理由购买了该开发板.     [1]主要原因,有人约我一起学习一起使用该 ...

  7. Asp.Net 之 基本控件FileUpload上传控件

    1.前台代码: <asp:FileUpload ID="FileUpload" runat="server" /> <asp:Button I ...

  8. LNMP一键安装包-CentOS 5/6下自动编译安装Nginx,MySQL,PHP

    适用环境: 系统支持:CentOS-5 (32bit/64bit).CentOS-6 (32bit/64bit) 内存要求:≥128M 安装了什么: 1.Nginx-1.2.0 2.MySQL 5.5 ...

  9. winform 上传

    public class ImitateSelectFile { public void Select(HtmlElement htmlEle, string fileFullPath) { html ...

  10. MVC 表单提交提示:已添加了具有相同键的项。

    MVC:页面提交的时候报如下错误: 解决方案: 这个Model 里面定义了重复的字段so~~~