socket计算机网络

大话-详解TCP/IP及C#-Socket实现

2018-06-02  本文已影响8人  fzq142

1.在Excel上写的内容,有TCP连接到断开的解析,直接粘贴出来


image.png

2.用C#语言来简单实现TCP连接到断开
①服务端

namespace TcpServer
{
    /// <summary>
    /// 步骤:绑定服务器IP和端口->监听客户端连接->传输数据->关闭与客户端的连接
    /// </summary>
    class SimpleServer
    {
        private Socket mSocket = null;

        private SimpleServer mSimpleServer = null;

        private byte[] mReceiveBuffer = null;
        private int mBufferIndex;

        public SimpleServer()
        {
            mSimpleServer = this;

            mReceiveBuffer = new byte[1024];
            mBufferIndex = 0;
        }

        /// <summary>
        /// 绑定ip 和端口
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public SimpleServer Bind(string ip, int port)
        {
            mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress iPAddress = IPAddress.Parse(ip);
            IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);

            mSocket.Bind(iPEndPoint);

            return mSimpleServer;
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="queueCount"></param>
        /// <returns></returns>
        public SimpleServer Listen(int queueCount)
        {
            //0:不处理队列,>0:最多处理的队列长度。
            mSocket.Listen(queueCount);

            return mSimpleServer;
        }

        /// <summary>
        /// 异步传输数据(这里暂时仅实现异步接收)
        /// </summary>
        /// <returns></returns>
        public SimpleServer StartTransmission()
        {
            mSocket.BeginAccept(AsyncAcceptCallback, mSocket);

            return mSimpleServer;
        }

        private void AsyncAcceptCallback(IAsyncResult ar)
        {
            //获取自定义的对象
            Socket socket = ar.AsyncState as Socket;
            //异步接受传入的连接尝试,并创建一个新 Socket 来处理远程主机通信。
            Socket clientSocket = socket.EndAccept(ar);

            string helloStr = "Hello Client! It is Server!";
            byte[] helloByte = Encoding.UTF8.GetBytes(helloStr);
            clientSocket.Send(helloByte);

            clientSocket.BeginReceive(mReceiveBuffer,
                mBufferIndex,
                RemainSize,
                SocketFlags.None,
                AsyncReceiveCallback,
                clientSocket);

            socket.BeginAccept(AsyncAcceptCallback, socket);
        }

        private void AsyncReceiveCallback(IAsyncResult ar)
        {
            Socket clientSocket = null;
            try
            {
                clientSocket = ar.AsyncState as Socket;
                int count = clientSocket.EndReceive(ar);
                if(count == 0)
                {
                    //接收不到数据,说明客户端已经关闭,那在服务端这里要关闭 Socket
                    clientSocket.Close();
                    Console.WriteLine("客户端已经关闭");
                    return;
                }
                else
                {
                    MoveBufferIndex(count);
                    ReadReceiveData();
                    clientSocket.BeginReceive(mReceiveBuffer,
                        mBufferIndex,
                        RemainSize,
                        SocketFlags.None,
                        AsyncReceiveCallback,
                        clientSocket);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                if(clientSocket != null)
                {
                    clientSocket.Close();
                    Console.WriteLine("客户端已经关闭");
                }
            }
            finally
            {
                //有没有异常最后都要做的:
            }
        }

        public void CloseServer()
        {
            mSocket.Close();
        }

        /// <summary>
        /// 剩余的 buffer 数量
        /// </summary>
        private int RemainSize
        {
            get{ return (1024 - mBufferIndex); }
        }

        private void MoveBufferIndex(int value)
        {
            mBufferIndex += value;
        }

        private void ReadReceiveData()
        {
            while(true)
            {
                int length = mBufferIndex - 4;
                if(length <= 0)
                {
                    return;
                }
                int count = BitConverter.ToInt32(mReceiveBuffer, 0);
                if(length >= count)
                {
                    string receiveStr = Encoding.UTF8.GetString(mReceiveBuffer, 4, count);
                    Console.WriteLine("解析接受到的数据:" + receiveStr);
                    mBufferIndex -= (4 + count);
                    Array.Copy(mReceiveBuffer, 4 + count, mReceiveBuffer, 0, mBufferIndex);
                }
                else
                {
                    return;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SimpleServer simpleServer = new SimpleServer();

            simpleServer.Bind("127.0.0.1", 6666)
                .Listen(10)
                .StartTransmission();

            Console.ReadLine();
        }
    }
}

②客户端

namespace TcpClient
{
    /// <summary>
    /// 过程:连接服务端-->数据交互-->断开连接
    /// </summary>
    class SimpleClient
    {
        private Socket mSocket = null;

        private SimpleClient mSimpleClient = null;

        private byte[] mReceiveBuffer = null;

        public SimpleClient()
        {
            mSimpleClient = this;

            mReceiveBuffer = new byte[1024];
        }

        public SimpleClient ConnetServer(string ip, int port)
        {
            mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress iPAddress = IPAddress.Parse(ip);
            IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);
            mSocket.Connect(iPEndPoint);

            return mSimpleClient;
        }

        public void Receive()
        {
            int count = mSocket.Receive(mReceiveBuffer);
            string receiveMsg = Encoding.UTF8.GetString(mReceiveBuffer, 0, count);
            Console.WriteLine(receiveMsg);
        }

        public void Send(byte[] dataByte)
        {
            mSocket.Send(dataByte);
        }

        public void Close()
        {
            mSocket.Close();
        }
        /// <summary>
        /// 将字符串转换为 byte数组
        /// </summary>
        /// <param name="dataStr">要转换的字符串</param>
        /// <returns>byte数组</returns>
        public byte[] String2Bytes(string dataStr)
        {
            byte[] dataByte = Encoding.UTF8.GetBytes(dataStr);
            byte[] dataBytelength = BitConverter.GetBytes(dataByte.Length);
            byte[] newByte = dataBytelength.Concat(dataByte).ToArray();
            return newByte;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SimpleClient simpleClient = new SimpleClient();
            simpleClient.ConnetServer("127.0.0.1", 6666);
            simpleClient.Receive();
            simpleClient.Send(simpleClient.String2Bytes("send somethings to server..."));
            Console.ReadKey();
            simpleClient.Close();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读