c# TCP protocol

1.tcp protocol

###Definition of tcp protocol:

1. TCP Protocol Transmission Control Protocol (TCP
) is a connection-oriented, reliable, byte stream-based transport layer communication protocol, defined by IETF's RFC 793.

TCP is designed to accommodate a layered protocol hierarchy that supports multiple network applications.
TCP is relied upon to provide reliable communication services between pairs of processes in a host computer connected to different but interconnected computer communication networks. TCP assumes that it can obtain simple, possibly unreliable datagram services from lower-level protocols.
In principle, TCP should be able to operate on top of a variety of communications systems, from hardwired connections to packet-switched or circuit-switched networks.

Advantages of tcp protocol:

It has the characteristics of orderly, safe, reliable, not easy to lose packets, and high latency.

tcp: used for chatting and transferring files

2.Basic connection of TCP protocol

2.1TCP protocol server

 private static void StartService()
        {
    
    
            //tcp :协议端
            //实例化一个Tcp协议的socket对象
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //给服务器绑定地址与端口
            IPAddress ipaddress = IPAddress.Parse("192.168.218.12");
            IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, 7999);
            //把ip与端口绑定在Socket里面
            socketServer.Bind(iPEndPoint);
            //侦听
            socketServer.Listen(100);
            Console.WriteLine("tcp启动");
            Task.Run(() =>
            {
    
    
                while (true)//循环等待客户端连接
                {
    
    
                    //会等待客户端的连接,会卡在这里,不往下运行,直到有下一个宽带连接才会继续往下运行
                    //当有客户端连接的时候,会返回客户端连接的对象
                    Socket socketkint = socketServer.Accept();
                    byte[] byteff = encoding.GetBytes("你今天吃饭了吗");
                    socketkint.Send(byteff);
                    Task.Run(() =>
                    {
    
    
                        try
                        {
    
    
                            while (true)//循环接收数据
                            {
    
    
                                //接受数据
                                byte[] buffer = new byte[1024];
                                //返回接收到的数据大小,接收数据也会卡住,只有接收到数据的时候才会继续往下进行
                                int longth = socketkint.Receive(buffer);
                                if (longth == 0)
                                {
    
    
                                    Console.WriteLine("一个客户端断开连接");
                                    return;
                                }
                                //把字符转成字符串
                                string str = encoding.GetString(buffer, 0, longth);
                                Console.WriteLine(str);
                            }
                        }
                        catch (Exception ex)
                        {
    
    
                            Console.WriteLine("出现异常" + ex.Message);
                            return;
                        }
                        finally
                        {
    
    
                            socketkint.Close();
                        }

                    });
                }
            });
        }

2.2 Client of TCP protocol

   private static void StartClient()
        {
    
    
           

            //实例化一个TCP协议的Socket对象
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服务端的地址和端口
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("192.168.218.12"), 7999);
            try
            {
    
    
                //连接远程的服务端
                socket.Connect(iPEndPoint);
                Console.WriteLine("连接服务端成功");
            }
            catch (Exception ex)
            {
    
    
                Console.WriteLine("连接异常:" + ex.ToString());
                return;
            }
            //循环接收数据
            Task.Run(() =>
            {
    
    
                try
                {
    
    
                    while (true)
                    {
    
    
                        byte[] buffer = new byte[1024];
                        //等待接收对方发送的数据,返回对方发送数据的长度,数据会存放在buffer里面
                        int length = socket.Receive(buffer);
                        //把byte[]转成字符串
                        string str = encoding.GetString(buffer, 0, length);
                        Console.WriteLine(str);
                    }
                }
                catch (Exception ex)
                {
    
    
                    Console.WriteLine("出现异常:" + ex.Message);
                }
                finally
                {
    
    
                    //关闭连接,释放资源
                    socket.Close();
                }
            });
            //循环发送数据
            Task.Run(async () =>
            {
    
    
                try
                {
    
    
                    int num = 1;
                    while (true)
                    {
    
    
                        byte[] buffer = encoding.GetBytes("我是客户端" + num);
                        //发送数据
                        socket.Send(buffer);
                        num++;
                        //等待1000毫秒
                        await Task.Delay(1000);
                    }
                }
                catch (Exception ex)
                {
    
    
                    Console.WriteLine("出现异常:" + ex.Message);
                }
            });

        }

3.TCP file transfer:

3.1 Server:

public static void StartFileServer()
        {
    
    
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketServer.Bind(new IPEndPoint(IPAddress.Any, 8500));
            socketServer.Listen(100);
            Console.WriteLine("客户端启动");
            ServerAccept();
        }

        //等待客户端连接
        private static void ServerAccept()
        {
    
    
            Task.Run(() =>
            {
    
    
                while (true)
                {
    
    
                    //等待客户端的连接
                    Socket socketClient = socketServer.Accept();
                    Console.WriteLine("客户端上线了");
                    //接收客户端的消息
                    byte[] buffer = new byte[1024];
                    int length = socketClient.Receive(buffer);
                    //接收文件信息的消息
                    string str = encoding.GetString(buffer, 0, length);
                    string[] strs = str.Split('-');
                    //文件大小
                    long fileSize = Convert.ToInt64(strs[0]);
                    string fileName = strs[1];
                    //给客户端回复"OK"
                    FileStream stream = System.IO.File.Create($"F:\\dfile\\{
      
      fileName}");
                    socketClient.Send(encoding.GetBytes("OK"));
                   // 接收客户端的文件
                    long NowSize = 0;
                    Console.WriteLine("正在接收...");
                    while (true)
                    {
    
    
                        buffer = new byte[1024 * 10];
                        length = socketClient.Receive(buffer);
                       // 把读到的数据写入文件
                        stream.Write(buffer, 0, length);
                        NowSize += length;
                        //读取结束
                        if (NowSize == fileSize)
                        {
    
    
                            break;
                        }
                    }
                        stream.Close();
                        socketClient.Close();
                }
            });

        }

3.2 Client:

//启动客户端
        private static void ClientServer()
        {
    
    
            //连接服务端
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.218.12"), 8500));
            string fullname = "F:\\df1\\a.txt";
            //读取文件名及其后缀
            string filename = Path.GetFileName(fullname);
            FileStream fs = File.OpenRead(fullname);
            socketClient.Send(encoding.GetBytes($"{
      
      fs.Length}-{
      
      filename}"));
            //接收服务端消息"OK"
            byte[] buffer = new byte[100];
            int iength = socketClient.Receive(buffer);
            string str = Encoding.UTF8.GetString(buffer, 0, iength);
            if (str != "OK")//不是"OK"
            {
    
    
                fs.Close();
                socketClient.Close();
                return;
            }
            Console.WriteLine("努力加载中...");
            //发送文件
            Task.Factory.StartNew(() =>
            {
    
    
                buffer = new byte[1024 * 10];
                while (true)
                {
    
    
                    int length = fs.Read(buffer, 0, buffer.Length);
                    if (length == 0)//为0是发送结束
                    {
    
    
                        fs.Close() ;
                        socketClient.Close();
                        Console.WriteLine("发送结束");
                        break;
                    }
                    socketClient.Send(buffer, 0, length, SocketFlags.None);
                }
            });
        }

4.TCP hexadecimal conversion

4.1 Server

 private static void StartServer()
        {
    
    
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Any, 8500));
            socket.Listen(10);
            Console.WriteLine("客户端启动");
            Task.Run(() =>
            {
    
    
                Socket socketClient = socket.Accept();
                Console.WriteLine("客户上线");
                while (true)
                {
    
    
                    //收到客户端消息
                    byte[] buffer = new byte[1024];
                    int length = socketClient.Receive(buffer);
                    /*byte[] data = new byte[length];
                    string str = string.Empty;
                    for (int i = 0; i < length; i++)
                    {
                        str += $"{buffer[i].ToString("x2")}";
                        data[i] = (byte)(buffer[i] + 1);
                    }
                    Console.WriteLine("收到的客户端消息"+str);
                    //收到客户端消息+1给客户端回复过去
                    socketClient.Send(data);*/
                    if (length == 1)
                    {
    
    
                        byte data = buffer[0];
                        if (data == 0x0A)
                        {
    
    
                            byte tem = (byte)(random.Next(0, 50));
                            socketClient.Send(new byte[] {
    
     tem });
                        }
                        else if (data == 0x0B)
                        {
    
    
                            byte hum = (byte)(random.Next(0, 50));
                            socketClient.Send(new byte[] {
    
     hum });
                        }
                    }


                }
            });
        }

4.2 Client

 private static void StartClient()
        {
    
    
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(new IPEndPoint(IPAddress.Parse("192.168.218.12"), 8500));
            Task.Run(async () =>
            {
    
    
                while (true)
                {
    
    
                    //socket.Send(new byte[] { 0xAA, 0xAB, 0xAC });
                    /*     byte[] buffer = new byte[1024];
                         int len = socket.Receive(buffer);
                         string str = string.Empty;
                         for (int i = 0; i < len; i++)
                         {
                             str += $"{buffer[i].ToString("x2")}";

                         }
                         Console.WriteLine("发送的消息" + str);*/
                    int num = random.Next(0, 100);
                    byte cmd = (byte)(num % 2 == 0 ? 0x0A : 0x0B);
                    socket.Send(new byte[] {
    
     cmd });
                    byte[] buffer = new byte[1024];
                    int length = socket.Receive(buffer);
                    if (length == 1)
                    {
    
    
                        byte data = buffer[0];
                        if (cmd == 0x0A)
                        {
    
    
                            Console.WriteLine("a" + data);
                        }
                        else if (cmd == 0x0B)
                        {
    
    
                            Console.WriteLine("b" + data);
                        }
                    }
                    await Task.Delay(200);
                }
            });
        }

Guess you like

Origin blog.csdn.net/qq_57212959/article/details/130753389