博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#简单的tcpserver
阅读量:4579 次
发布时间:2019-06-09

本文共 3511 字,大约阅读时间需要 11 分钟。

实现一个简单的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, 3000);            this.listenThread = new Thread(new ThreadStart(ListenForClients));            this.listenThread.Start();            Console.WriteLine("Server started at {0} :{1} @ {2}", IPAddress.Any, 1031, 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[4096];            int bytesRead=0;            //bool isRight=false;                        while (true)            {                bytesRead = 0;                try                {                    //blocks until a client sends a message                    bytesRead = clientStream.Read(message, 0, 4096);                }                catch                {                    //a socket error has occured                    Console.WriteLine("Error:receive msg error");                    break;                }                if (bytesRead == 0)                {                    //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, 0, 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=="101")                {                    //isRight = true;                    sendstr = "202";                    Console.ForegroundColor = ConsoleColor.Red;                }                else                {                    Console.ForegroundColor = ConsoleColor.White;                }                byte[] buffer = encoder.GetBytes(sendstr);                clientStream.Write(buffer, 0, buffer.Length);                clientStream.Flush();                               Console.WriteLine("Sent:[{1}]:msg:@[{0}] @{2}\r\n", sendstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());            }            tcpClient.Close();        }    }}

 

转载于:https://www.cnblogs.com/qiri07/p/4321902.html

你可能感兴趣的文章
JS进阶
查看>>
pwnable random
查看>>
silverlight 控件自定义样式 实现方法
查看>>
VirtualBox Cannot register the hard disk
查看>>
Linux的yum的配置
查看>>
tornado调用ioloop TracebackFuture实现非堵塞的模块
查看>>
chrome桌面通知notification
查看>>
codeforces 916E Jamie and Tree dfs序列化+线段树+LCA
查看>>
个人阅读作业+总结
查看>>
caffe.bin caffe的框架
查看>>
maven+springmvc+spring+mybatis+velocity整合
查看>>
1.Java集合框架剖析
查看>>
学习使用C语言实现线性表
查看>>
跨平台移动开发 Android使用JPush推送消息
查看>>
虚拟机里linux系统安装 CentOS 64-bit(6.4版本)——笔记
查看>>
【原】常用工具集合(一)
查看>>
ROC曲线和PR曲线绘制【转】
查看>>
[dp]uestc oj E - 菲波拉契数制
查看>>
03. PNG,GIF,JPG的区别及如何选?
查看>>
Linux-SHELL脚本学习
查看>>