XCStudio

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Reflection;

namespace ConsoleApplication1
{
    public class Program
    {
        Thread[] SocketThreadList = new Thread[100];

        static Socket TCPListen = null;

        static void Main(string[] args)
        {
            TCPListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            IPEndPoint LocalPort = new IPEndPoint(IPAddress.Any, 55000);

            TCPListen.Bind(LocalPort); TCPListen.Listen(100);

            Thread AcceptThread = new Thread(new ThreadStart(AcceptWorkThread));

            AcceptThread.Start();

            Console.WriteLine("****** 软创通信服务器程序 ******");

            Console.WriteLine(string.Format("开始监听 <{0}>", LocalPort));

            Console.WriteLine("单击回车键退出SOCKET");

            Console.ReadLine(); GC.Collect(); GC.WaitForPendingFinalizers();
        }

        // 接收连接线程
        [STAThread]
        static void AcceptWorkThread()
        {
            // 指示为后台线程
            Thread.CurrentThread.IsBackground = true;

            while (true)
            {
                // 为新建连接创建新的Socket实例
                Socket s_Accept = TCPListen.Accept();

                IPEndPoint remoteAddress = (IPEndPoint)s_Accept.RemoteEndPoint;

                Console.WriteLine(string.Format("接收到来自 {0} 的连接", remoteAddress));

                // 接收数据专用线程

                Thread ReceiveThread = new Thread(new ParameterizedThreadStart(ReceiveWorkThread));

                ReceiveThread.Start(s_Accept);

                Thread.Sleep(100);
            }
        }

        static void ReceiveWorkThread(object obj)
        {
            Thread.CurrentThread.IsBackground = true;   // 标识后台线程

            Socket s_Receive = (Socket)obj;

            byte[] buffer = new byte[1024];     // 创建接收缓冲

            IPEndPoint remoteAddress = (IPEndPoint)s_Receive.RemoteEndPoint;

            try
            {
                while (s_Receive.Connected)
                {
                    if (s_Receive.Connected)
                    {

                        int ReceiveCount = s_Receive.Receive(buffer);

                        Console.WriteLine(string.Format("{0}:{1}", remoteAddress, Encoding.Default.GetString(buffer)));

                        // 返回接收成功数据
                        s_Receive.Send(Encoding.Default.GetBytes("AAA"));

                        Thread.Sleep(100);
                    }
                    else { s_Receive.Close(); break; }
                }
            }
            catch { Console.WriteLine(string.Format("{0} 断开连接", remoteAddress)); }
        }
    }
}
posted on 2010-07-01 08:42  xiaochao2012  阅读(1067)  评论(0编辑  收藏  举报