C#TCP服务器简单程序


参考网上的程序写的,仅仅都是概念,离实际应用还差十万八千里

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

用到这三个库。

            IPAddress local = IPAddress.Any;
            IPEndPoint iep = new IPEndPoint(local, 9000);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(iep);
            server.Listen(20);

            Thread tcpThread = new Thread(new ThreadStart(TcpListen));
            tcpThread.Start();
        private void TcpListen()
        {
            while (true)
            {
                try
                {
                    Socket client = server.Accept();
                    ClientThread newClient = new ClientThread(client);
                    Thread newThread = new Thread(new ThreadStart(newClient.ClientService));
                    newThread.Start();
                }
                catch { }
            }
        }
class ClientThread
    {
        public Socket client = null;
        int i;
        public ClientThread(Socket k)
        {
            client = k;
        }
        public void ClientService()
        {
            string data = null;
            byte[] bytes = new byte[4096];
            Console.WriteLine("新用户的连接。。。");
            try
            {
                while ((i = client.Receive(bytes)) != 0)
                {
                    if (i < 0)
                    {
                        break;
                    }
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("收到数据: {0}", data);
                    data = data.ToUpper();
                    bytes = System.Text.Encoding.ASCII.GetBytes(data);
                    client.Send(bytes);
                }
            }
            catch (System.Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            client.Close();
            Console.WriteLine("用户断开连接。。。");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值