C#线程池多线程Socket通讯 服务器端和客户端示例

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

namespace socket2016
{
    class Program
    {
        static void Main(string[] args)
        {
            //服务器端
            Socket sktltn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sktltn.Bind(new IPEndPoint(IPAddress.Any, 12345));
            sktltn.Listen(30);
            while (true)
            {
                Socket sk = sktltn.Accept();
                //ThreadPool.SetMaxThreads(10, 10);
                ThreadPool.QueueUserWorkItem(p =>
                {
                    Socket skc = (Socket)sk;
                    byte[] array = new byte[10240];
                    int offset = 0;
                    while (true)
                    {
                        int len = skc.Receive(array, offset, array.Length - offset, SocketFlags.None);
                        if (len == 0)
                        {
                            break;
                        }
                        offset += len;
                    }
                    string content = Encoding.UTF8.GetString(array, 0, offset);
                    Console.WriteLine("> " + content);
                }, sk);
            }
        }
    }
}

 

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

namespace socket2016Client
{
    class Program
    {
        static void Main(string[] args)
        {
            //客户端
            Console.WriteLine("输入文字,回车发送");
            while (true)
            {
                string str = Console.ReadLine();
                if (str.Length > 0)
                {
                    Socket sktc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sktc.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345));
                    byte[] bytes = Encoding.UTF8.GetBytes(str);
                    int offset = 0;
                    while ((offset += sktc.Send(bytes, offset, bytes.Length - offset, SocketFlags.None)) < bytes.Length) ;
                    sktc.Close();
                }
            }
        }
    }
}



posted @ 2016-05-18 09:25  深南大道  阅读(1643)  评论(0编辑  收藏  举报