TcpServer - 副本.cs 6.0 KB
using System;
using System.Text;
using System.Windows.Forms;

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


namespace OnlineStore.Common
{
    public class TcpServer
    {
        public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private Thread m_serverThread;
        private Socket m_serverSocket;

        public delegate void ReceiveMessageDelegate(Client client);
        ReceiveMessageDelegate receiveMessageDelegate;

        private void logLocalIp()
        {
            string[] addresses = GetLocalAddresses();
            string iplist = "本机IP:[";
            if (addresses.Length > 0)
            {
                for (int i = 0; i < addresses.Length; i++)
                {
                    if (addresses.Length != 0)
                    {
                        iplist = iplist + " " + addresses[i];
                    }
                }
            } 
            LogUtil.info(LOGGER, iplist + "]");
        }

        /// <summary>
        /// 开始服务
        /// </summary>
        public void Start(int m_serverPort)
        {
            try
            {  
                m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, m_serverPort);

                m_serverSocket.Bind(localEndPoint);
                m_serverSocket.Listen(10);

                m_serverThread = new Thread(new ThreadStart(ReceiveAccept));
                m_serverThread.Start();

                LogUtil.info(LOGGER, " Server start listen : " + m_serverPort);
                logLocalIp();


                //this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server started.");
            }
            catch (SocketException se)
            {
                throw new Exception(se.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        public void Stop()
        {
            try
            {
                m_serverThread.Abort(); // 线程终止
                m_serverSocket.Close(); // Socket Close

                //this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server stoped.");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void ReceiveAccept()
        {
            while (true)
            {
                Client client = new Client();

                try
                {
                    client.ClientSocket = m_serverSocket.Accept();
                    //this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client[" + client.ClientSocket.RemoteEndPoint.ToString() + "] connected.");

                    receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
                    receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        private void ReceiveMessages(Client client)
        {
            try
            {
                while (true)
                {
                    byte[] receiveBuffer = new byte[1024];

                    //int size = ;
                    int size = client.ClientSocket.Receive(receiveBuffer);

                    string strReceiveData = Encoding.ASCII.GetString(receiveBuffer, 0, size);

                    if (!string.IsNullOrEmpty(strReceiveData))
                    {
                        LogUtil.info(LOGGER, "收到数据:" + strReceiveData);
                        // this.AddRunningInfo(">> Receive data from [" + client.ClientSocket.RemoteEndPoint.ToString()+ "]:" + strReceiveData);
                        string strSendData = "OK. The content is:" + strReceiveData;
                        //LogUtil.info(LOGGER, "OK. The content is:" + strReceiveData);
                        int sendBufferSize = Encoding.Unicode.GetByteCount(strSendData);
                        byte[] sendBuffer = new byte[sendBufferSize];
                        sendBuffer = Encoding.Unicode.GetBytes(strSendData);

                        client.ClientSocket.Send(sendBuffer);
                    }
                }
            }
            catch (SocketException e)
            {
                LogUtil.error(LOGGER, e.ToString());
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex.ToString());
            }
        }

        private void ReceiveMessagesCallback(IAsyncResult AR)
        {
            try
            {
                receiveMessageDelegate.EndInvoke(AR);
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取本机地址列表
        /// </summary>
        public string[] GetLocalAddresses()
        {
            // 获取主机名
            string strHostName = Dns.GetHostName();

            // 根据主机名进行查找
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);

            string[] retval = new string[iphostentry.AddressList.Length];

            int i = 0;
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                if (ipaddress.AddressFamily != AddressFamily.InterNetworkV6)
                {
                    retval[i] = ipaddress.ToString();
                    i++;
                }
            }
            return retval;
        }
    }

    /// <summary>
    /// 客户端会话信息类
    /// </summary>
    public class Client
    {
        Socket m_clientSocket;

        public Client() { }

        public Socket ClientSocket
        {
            get { return m_clientSocket; }
            set { this.m_clientSocket = value; }
        }
    }

}