Socket与TCPIP通讯

通讯基类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace lajiSocket
{
    public class AsynchronousSocketListener : IDisposable, IServer
    {
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        private Socket server;
        private List<RemoteData> _remotelist;
        private bool _listened = false;
        public AsyncCallback pfnWorkerCallBack;
        private IPAddress _ipAddress;
        private int _port;
        public event EventHandler<ReceivedInfoEventArgs> DataReceived;
        public bool IsServerOn
        {
            get
            {
                return this._listened;
            }
        }
        private AsynchronousSocketListener()
        {
        }
        public AsynchronousSocketListener(string ip, int port)
        {
            this._ipAddress = IPAddress.Parse(ip);
            this._port = port;
        }
        public void SendData(object sender, string data)
        {
            for (int i = 0; i < _remotelist.Count; i++)
            {
                RemoteData remoteData = (RemoteData)_remotelist[i];
                this.Send(remoteData.WorkSocket, data);
            }

        }
        public void ServerOn()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartListening));
        }
        public void StartListening(object obj)
        {
            IPEndPoint localEP = new IPEndPoint(this._ipAddress, this._port);
            this.server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                this.server.Bind(localEP);
                this.server.Listen(10);
                this._listened = true;
                while (true)
                {
                    AsynchronousSocketListener.allDone.Reset();
                    if (this.server == null)
                    {
                        break;
                    }
                    this.server.BeginAccept(new AsyncCallback(this.AcceptCallback), this.server);
                    AsynchronousSocketListener.allDone.WaitOne();
                }
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (SocketException ex2)
            {
                //MessageBox.Show(ex2.ErrorCode.ToString() + ": " + ex2.Message, "Socket Error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
            catch (Exception ex3)
            {
                //MessageBox.Show(ex3.ToString() + "\r\n" + ex3.Message);
            }
        }
        public void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                AsynchronousSocketListener.allDone.Set();
                if (this._listened)
                {
                    Socket socket = (Socket)ar.AsyncState;
                    if (socket != null)
                    {
                        Socket socket2 = socket.EndAccept(ar);
                        string text = socket2.RemoteEndPoint.ToString();
                        Console.WriteLine(socket2.RemoteEndPoint.ToString() + " 已连接");
                        RemoteData remoteData = new RemoteData(socket2, socket2.RemoteEndPoint);
                        if (this._remotelist == null)
                        {
                            this._remotelist = new List<RemoteData>();
                        }
                        this._remotelist.Add(remoteData);
                        this.WaitForData(remoteData);
                    }
                }
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            catch (Exception ex2)
            {
            }
        }
        public void WaitForData(RemoteData remoteData)
        {
            try
            {
                if (this.pfnWorkerCallBack == null)
                {
                    this.pfnWorkerCallBack = new AsyncCallback(this.ReadCallback);
                }
                StateObject stateObject = new StateObject();
                stateObject.workSocket = remoteData.WorkSocket;
                remoteData.WorkSocket.BeginReceive(stateObject.buffer, 0, 1024, SocketFlags.None, this.pfnWorkerCallBack, stateObject);
            }
            catch (SocketException ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        public void ReadCallback(IAsyncResult ar)
        {
            try
            {
                string data = string.Empty;
                StateObject stateObject = (StateObject)ar.AsyncState;
                Socket workSocket = stateObject.workSocket;
                int num = workSocket.EndReceive(ar);
                RemoteData remoteData = new RemoteData(workSocket, workSocket.RemoteEndPoint);
                if (num == 0)
                {
                    bool flag = false;
                    int index = 0;
                    for (int i = 0; i < this._remotelist.Count; i++)
                    {
                        if (this._remotelist[i].RemoteEndPoint == remoteData.RemoteEndPoint)
                        {
                            flag = true;
                            index = i;
                            break;
                        }
                    }
                    if (flag)
                    {
                        this._remotelist.RemoveAt(index);
                    }
                    Console.WriteLine(remoteData.RemoteEndPoint.ToString() + " 远程已断开");
                    //Log.WriteLog(remoteData.RemoteEndPoint.ToString() + " 远程已断开");
                }
                if (num > 0)
                {
                    stateObject.sb.Append(Encoding.ASCII.GetString(stateObject.buffer, 0, num));
                    data = stateObject.sb.ToString();
                    ReceivedInfoEventArgs e = new ReceivedInfoEventArgs(data, remoteData);
                    this.OnReceived(e);
                    stateObject.sb.Remove(0, stateObject.sb.Length);
                    RemoteData remoteData2 = new RemoteData(workSocket, workSocket.LocalEndPoint);
                    this.WaitForData(remoteData2);
                }
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            catch (Exception ex2)
            {
                //MessageBox.Show(ex2.ToString());
            }
        }
        protected virtual void OnReceived(ReceivedInfoEventArgs e)
        {
            EventHandler<ReceivedInfoEventArgs> dataReceived = this.DataReceived;
            if (dataReceived != null)
            {
                dataReceived(this, e);
            }
        }
        private void Send(Socket handler, string data)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(data);
            handler.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(this.SendCallback), handler);
        }
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket socket = (Socket)ar.AsyncState;
                int num = socket.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", num);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }
        public void Dispose()
        {
            if (this.server != null)
            {
                this.server.Close();
                this.server = null;
                this._listened = false;
            }
            if (this._remotelist != null)
            {
                int count = this._remotelist.Count;
                for (int i = 0; i < count; i++)
                {
                    if (this._remotelist[i].WorkSocket != null)
                    {
                        if (this._remotelist[i].WorkSocket.Connected)
                        {
                            this._remotelist[i].WorkSocket.Shutdown(SocketShutdown.Both);
                            this._remotelist[i].WorkSocket.Close();
                        }
                    }
                }
                this._remotelist.Clear();
                //Log.WriteLog("远程连接已断开");
            }
        }
    }

    public class TcpLink
    {
        /// <summary>
        ///网口号 
        /// </summary>
        public int m_nIndex;
        /// <summary>
        ///网口定义 
        /// </summary>
        public string m_strName;
        /// <summary>
        ///对方IP地址 
        /// </summary>
        public string m_strIP;
        /// <summary>
        ///端口号 
        /// </summary>
        public int m_nPort;
        /// <summary>
        ///超时时间 
        /// </summary>
        public int m_nTime;
        /// <summary>
        ///命令分隔 
        /// </summary>
        public string m_strLineFlag;

        /// <summary>
        ///命令分隔符 
        /// </summary>
        private string m_strLine;

        private TcpClient m_client = null;
        private bool m_bTimeOut = false;

        /// <summary>
        /// 状态变更委托函数定义
        /// </summary>
        /// <param name="tcp"></param>
        public delegate void StateChangedHandler(TcpLink tcp);
        /// <summary>
        /// 状态变更委托事件
        /// </summary>
        public event StateChangedHandler StateChangedEvent;

        private static bool m_bConnectSuccess = false;
        private static Exception socketException;
        private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="nIndex"></param>
        /// <param name="strName"></param>
        /// <param name="strIP"></param>
        /// <param name="nPort"></param>
        /// <param name="nTime"></param>
        /// <param name="strLine"></param>
        public TcpLink(int nIndex, string strName, string strIP, int nPort, int nTime, string strLine)
        {
            m_nIndex = nIndex;
            m_strName = strName;
            m_strIP = strIP;
            m_nPort = nPort;
            m_nTime = nTime;

            m_strLineFlag = strLine;
            if (strLine == "CRLF")
            {
                m_strLine = "\r\n";
            }
            else if (strLine == "CR")
            {
                m_strLine = "\r";
            }
            else if (strLine == "LF")
            {
                m_strLine = "\n";
            }
            else if (strLine == "无")
            {
                m_strLine = "";
            }
        }

        /// <summary>
        /// 判断是否超时
        /// </summary>
        /// <returns></returns>
        public bool IsTimeOut()
        {
            return m_bTimeOut;
        }

        /// <summary>
        ///网口打开时通过回调检测是否连接超时。 5秒种 
        /// </summary>
        /// <param name="asyncResult"></param>
        private static void CallBackMethod(IAsyncResult asyncResult)
        {
            try
            {
                m_bConnectSuccess = false;
                TcpClient tcpClient = asyncResult.AsyncState as TcpClient;
                if (tcpClient.Client != null)
                {
                    tcpClient.EndConnect(asyncResult);
                    m_bConnectSuccess = true;
                }
            }
            catch (Exception ex)
            {
                m_bConnectSuccess = false;
                socketException = ex;
            }
            finally
            {
                TimeoutObject.Set();
            }
        }

        /// <summary>
        ///打开网口 
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            if (m_client == null)
            {
                m_client = new TcpClient();
            }
            if (m_client.Connected == false)
            {
                m_client.SendBufferSize = 4096;
                m_client.SendTimeout = m_nTime;
                m_client.ReceiveTimeout = m_nTime;
                m_client.ReceiveBufferSize = 4096;

                try
                {
                    TimeoutObject.Reset();
                    socketException = null;
                    m_client.BeginConnect(m_strIP, m_nPort, new AsyncCallback(CallBackMethod), m_client);
                    if (TimeoutObject.WaitOne(5000, false))
                    {
                        if (m_bConnectSuccess)
                        {
                            if (StateChangedEvent != null)
                                StateChangedEvent(this);
                            return m_client.Connected;
                        }
                        else
                            throw socketException;
                    }
                    else
                    {
                        //                   m_client.Close();
                        throw new TimeoutException("TimeOut Exception");
                    }

                    //     m_client.Connect(m_strIP, m_nPort);
                }
                catch (Exception e)
                {
                    m_bTimeOut = true;
                    //Debug.WriteLine(string.Format("{0}:{1}{2}\r\n", m_strIP, m_nPort, e.Message));
                    if (StateChangedEvent != null)
                        StateChangedEvent(this);
                }
            }
            return m_client.Connected;
        }

        /// <summary>
        /// 判断网口是否打开
        /// </summary>
        /// <returns></returns>
        public bool IsOpen()
        {
            return m_client != null && m_client.Connected;
        }

        /// <summary>
        ///向网口写入数据 
        /// </summary>
        /// <param name="sendBytes"></param>
        /// <param name="nLen"></param>
        /// <returns></returns>
        public bool WriteData(byte[] sendBytes, int nLen)
        {
            if (m_client.Connected)
            {
                NetworkStream netStream = m_client.GetStream();
                if (netStream.CanWrite)
                {
                    netStream.Write(sendBytes, 0, nLen);
                }
                //netStream.Close();
                return true;
            }
            return false;
        }

        /// <summary>
        ///向网口写入字符串 
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public bool WriteString(string strData)
        {
            if (m_client.Connected)
            {
                NetworkStream netStream = m_client.GetStream();
                if (netStream.CanWrite)
                {
                    Byte[] sendBytes = Encoding.UTF8.GetBytes(strData);
                    netStream.Write(sendBytes, 0, sendBytes.Length);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        ///向网口写入一行字符 
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public bool WriteLine(string strData)
        {
            if (m_client.Connected)
            {
                NetworkStream netStream = m_client.GetStream();
                if (netStream.CanWrite)
                {
                    Byte[] sendBytes = Encoding.UTF8.GetBytes(strData + m_strLine);
                    netStream.Write(sendBytes, 0, sendBytes.Length);
                }
                //netStream.Close();
                return true;
            }
            return false;
        }

        /// <summary>
        ///从网口读取数据 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="nLen"></param>
        /// <returns></returns>
        public int ReadData(byte[] bytes, int nLen)
        {
            m_bTimeOut = false;
            int n = 0;
            if (m_client.Connected)
            {
                try
                {
                    NetworkStream netStream = m_client.GetStream();
                    if (netStream.CanRead)
                    {
                        n = netStream.Read(bytes, 0, nLen);
                        if (n > 0)
                        {
                        }
                    }
                }
                catch/*(TimeoutException e)*/
                {
                    m_bTimeOut = true;
                    if (StateChangedEvent != null)
                        StateChangedEvent(this);
                }
            }
            return n;
        }

        /// <summary>
        ///从网口读取一行数据 
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public int ReadLine(out string strData)
        {
            m_bTimeOut = false;
            strData = "";
            if (m_client.Connected)
            {
                try
                {
                    NetworkStream netStream = m_client.GetStream();
                    StringBuilder sb = new StringBuilder();
                    if (netStream.CanRead)
                    {
                        byte[] bytes = new byte[m_client.ReceiveBufferSize];
                        int n = netStream.Read(bytes, 0, (int)m_client.ReceiveBufferSize);
                        sb.Append(Encoding.UTF8.GetString(bytes, 0, n));
                        string str111111 = sb.ToString();
                        System.Diagnostics.Debug.WriteLine(str111111);
                        strData = str111111;
                    }
                }
                catch /*(TimeoutException e)*/
                {
                    m_bTimeOut = true;
                    if (StateChangedEvent != null)
                        StateChangedEvent(this);
                }
            }
            return strData.Length;
        }

        /// <summary>
        ///关闭网口 
        /// </summary>
        public void Close()
        {
            if (m_client != null)
            {
                if (m_client.Connected)
                {
                    NetworkStream netStream = m_client.GetStream();
                    netStream.Close();
                }
                m_client.Close();

                m_client = null;
                m_bTimeOut = false;
                if (StateChangedEvent != null)
                    StateChangedEvent(this);
            }
        }

        /// <summary>
        /// 清除缓冲区
        /// </summary>
        public void ClearBuffer()
        {
            if (m_client != null)
            {
                NetworkStream netStream = m_client.GetStream();
                m_client.GetStream().Flush();
                netStream.Close();
            }
        }
    }
    #region 代理类
    public class StateObject
    {
        public const int BufferSize = 1024;
        public Socket workSocket = null;
        public byte[] buffer = new byte[1024];
        public StringBuilder sb = new StringBuilder();
    }

    public delegate void ShowMsg(string text);

    public class RemoteData
    {
        private EndPoint _remoteEndPoint;
        private Socket _workSocket;
        public EndPoint RemoteEndPoint
        {
            get
            {
                return this._remoteEndPoint;
            }
            set
            {
                this._remoteEndPoint = value;
            }
        }
        public Socket WorkSocket
        {
            get
            {
                return this._workSocket;
            }
            set
            {
                this._workSocket = value;
            }
        }
        public RemoteData()
        {
        }
        public RemoteData(Socket workSocket, EndPoint endPoint)
        {
            this._remoteEndPoint = endPoint;
            this._workSocket = workSocket;
        }
    }

    public class ReceivedInfoEventArgs : EventArgs
    {
        private string _data;
        private RemoteData _rmtData;
        public RemoteData RmtData
        {
            get
            {
                return this._rmtData;
            }
            set
            {
                this._rmtData = value;
            }
        }
        public string Data
        {
            get
            {
                return this._data;
            }
            set
            {
                this._data = value;
            }
        }
        public ReceivedInfoEventArgs(string data, RemoteData rmtData)
        {
            this._data = data;
            this._rmtData = rmtData;
        }
    }


    internal class net_commmunition
    {
        private TcpClient tclient = new TcpClient();
        public void Open(string ip, string port)
        {
            int port2 = int.Parse(port);
            this.tclient.Connect(ip, port2);
        }
        public string Read()
        {
            string result = string.Empty;
            try
            {
                NetworkStream stream = this.tclient.GetStream();
                if (this.tclient.Available > 0)
                {
                    byte[] array = new byte[1024];
                    stream.Read(array, 0, 1024);
                    result = Encoding.ASCII.GetString(array);
                }
            }
            catch
            {
                //MessageBox.Show("通信连接中断");
            }
            return result;
        }
        public void Write(string str)
        {
            try
            {
                NetworkStream stream = this.tclient.GetStream();
                byte[] bytes = Encoding.ASCII.GetBytes(str);
                stream.Write(bytes, 0, bytes.Length);
            }
            catch
            {
                //MessageBox.Show("通信连接中断");
            }
        }
        public void Close()
        {
            this.tclient.Close();
        }
    }


    internal interface IServer
    {
        bool IsServerOn
        {
            get;
        }
        void SendData(object sender, string data);
        void ServerOn();
    }
    #endregion
}
 

测试demo:

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace lajiSocket
{
    public partial class Form1 : Form
    {
        AsynchronousSocketListener socketListener;
        TcpLink tcpLink;
        net_commmunition tc;
        string receiveData = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void IniServer(string ip, int port)
        {
            socketListener = new AsynchronousSocketListener(ip, 8000);
            if (socketListener != null)
            {
                socketListener.ServerOn();
            }
        }

        private void IniClient(string ip, int port)
        {
            //tcpLink = new TcpLink(0, "lrf", ip, port, 10000, "无");
             tc = new net_commmunition();
            tc.Open(ip, port.ToString());
            {
                Thread thread = new Thread(ReceiveData);
                thread.Start();
            }
        }
        private void ReceiveData()
        {
            while (true)
            {
                receiveData = tc.Read();
                if (receiveData.Contains("start"))
                {
                    Action action = new Action(() =>
                    {
                        txtMsg.AppendText("start");
                    });
                    action.BeginInvoke(null, null);
                }
                Thread.Sleep(10);
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (cbxIsServer.Checked)
            {
                IniServer(txtIp.Text.Trim(), 8000);
            }
            else
            {
                IniClient(txtIp.Text.Trim(), 8000);
            }
        }

        private void btnSender_Click(object sender, EventArgs e)
        {
            if(socketListener!=null)
            {
                socketListener.SendData(null, txtMsg.Text);
            }
        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值