实现一个简单的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. 图像的稀疏表示——ScSPM和LLC的总结

    前言 上一篇提到了SPM.这篇博客打算把ScSPM和LLC一起总结了.ScSPM和LLC其实都是对SPM的改进.这些技术,都是对特征的描述.它们既没有创造出新的特征(都是提取SIFT,HOG, RGB ...

  2. 0703-APP-Notification-statue-bar

    1.展示显示textTicker和仅仅有icon的两种情况:当參数showTicker为true时显示否则不显示 // In this sample, we'll use the same text ...

  3. Redis缓存 ava-Jedis操作Redis,基本操作以及 实现对象保存

    源代码下载: http://download.csdn.net/detail/jiangtao_st/7623113 1.Maven配置 <dependency> <groupId& ...

  4. [MODx] 8. Snippet get data, chunk display

    Simple Example: Lets process this chunk and output its value. We have this Chunk, called "Welco ...

  5. Android 通用获取Ip的方法(判断手机是否联网的方法)!!!

    大家好,我们这一节讲一下,Android获取Ip的一些方法,在我们开发中,有判断手机是否联网,或者想获得当前手机的Ip地址,当然WIFI连接的和 我们3G卡的Ip地址当然是不一样的. 首先我尝试了如下 ...

  6. UpdatePanel的用法

    UpdatePanel控件也是Ajax里用得最多的控件之中的一个,UpdatePanel控件是用来局部更新网页上的内容,网页上要局部更新的内容必须放在UpdatePanel控件里,他必须和上一次说的S ...

  7. mysql 高可用方案漫谈(一) 转阿里云

    https://yq.aliyun.com/articles/2237?spm=5176.blog2238.yqblogcon1.7.e5fyEy#index_section

  8. javascript关闭浏览器窗口

    var opened=window.open('about:blank','_self'); opened.close(); window.open 不被阻止 .open('_blank') 然后 t ...

  9. [018]C++ explicit构造函数

    explicit [英][ɪkˈsplɪsɪt][美][ɪkˈsplɪsɪt] adj.明确的,清楚的; 直言的; 详述的; 不隐瞒的; 看到上面的英文解释,我们应该就知道explicit构造函数是什 ...

  10. 将项目添加到Finder侧边栏和工具栏

    转: http://www.cnblogs.com/wormday/archive/2011/05/08/2039468.html 1.在侧边栏和工具栏右键,有相应的设置选项 2.可以将项目拖到侧边栏 ...