NetTCPServer.cs 4.7 KB
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Sockets;
using System.Net;
using System.IO;
using log4net;
using System.Text;
using OnlineStore.Common;

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

        /// <summary>
        /// TCP服务端监听
        /// </summary>
        TcpListener tcpsever = null;
        /// <summary>
        /// 监听状态
        /// </summary>
        bool isListen = false;

        public BindingList<NewClient> lstClient = new BindingList<NewClient>();

        public IPAddress[] getLoacalIPAddress()
        {
            IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
            return ipHostEntry.AddressList;
        }
        public delegate void ReviceData(NewClient client, string ip, byte[] data);
        public event ReviceData ReviceDataEvent;
        /// <summary>
        /// 开启TCP监听
        /// </summary>
        /// <returns></returns>
        public void StartTCPServer(int port)
        {
            try
            {
                tcpsever = new TcpListener(IPAddress.Any, port);

                tcpsever.Start();
                tcpsever.BeginAcceptTcpClient(new AsyncCallback(Acceptor), tcpsever);
                isListen = true;
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 停止TCP监听
        /// </summary>
        /// <returns></returns>
        public void StopTCPServer()
        {
            tcpsever.Stop();
            isListen = false;
        }

        /// <summary>
        /// 客户端连接初始化
        /// </summary>
        /// <param name="o"></param>
        private void Acceptor(IAsyncResult o)
        {
            TcpListener server = o.AsyncState as TcpListener;
            try
            {
                //初始化连接的客户端
                NewClient newClient = new NewClient();
                newClient.tcpClient = server.EndAcceptTcpClient(o); 
                lstClient.Add(newClient);

                newClient.tcpClient.GetStream().BeginRead(newClient.Buffer, 0, newClient.Buffer.Length, new AsyncCallback(TCPCallBack), newClient);
                server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//继续监听客户端连接
            }
            catch (ObjectDisposedException ex)
            { //监听被关闭
            }
            catch (Exception ex)
            {

            }
        }


        /// <summary>
        /// 对当前选中的客户端发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        public bool SendData(NewClient selClient, byte[] data)
        {
            try
            {
                selClient.tcpClient.GetStream().Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 客户端通讯回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void TCPCallBack(IAsyncResult ar)
        {
            NewClient client = (NewClient)ar.AsyncState;
            if (client.tcpClient.Connected)
            {
                NetworkStream ns = client.tcpClient.GetStream(); 
                StreamReader sr = new StreamReader(ns);
                string str = sr.ReadLine();
                LogUtil.info("读取到数据:"+str);
                byte[] recdata = new byte[ns.EndRead(ar)];
                if (recdata.Length > 0)
                {
                    //Array.Copy(client.Buffer, recdata, recdata.Length);

                    LogUtil.info("读取到数据1111:" + Encoding.ASCII.GetString(recdata));
                    //ns.BeginRead(client.Buffer, 0, client.Buffer.Length, new AsyncCallback(TCPCallBack), client);
                }
                else
                {
                    client.tcpClient.Close();
                    lstClient.Remove(client);
                }
            }
        }
        /// <summary>
        /// 清理
        /// </summary>
        public void ClearSelf()
        {
            foreach (NewClient client in lstClient)
            {
                client.tcpClient.Close();
            }
            lstClient.Clear();
            if (tcpsever != null)
            {
                tcpsever.Stop();
            }
        }
    }

    public class NewClient
    {
        public TcpClient tcpClient { get; set; }
        public byte[] Buffer = new byte[1024];
    }

}