c# TcpListener编写一个tcpserver服务器代码

代码语言:c#

所属分类:通讯

代码描述:c# TcpListener编写一个tcpserver服务器代码

代码标签: 一个 tcpserver 服务器

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace HelloWorldApplication
{
    class HelloWorld
    {
        static void Main(string[] args) {
            /* 我的第一个 C# 程序*/
            Console.WriteLine("Hello World!");
            Server s=new Server();
        }
    }
    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 unt.........完整代码请登录后点击上方下载按钮下载查看

网友评论0