SimpleTcpServer

class SimpleTcpServer
{
    static class bRB
    {
        //ASCII 'A' 0x41 65
        //ASCII 'B' 0x42 66
        //byte[] flag = { 65, 66 };
        //byte keyA = 0;    //随机密钥
        //byte keyB = 0;    //包字节数量<=4096。一个byte最大只有255.
        //key=keyA^keyB;    //想用异或字节解密,一次一加密。
        //byte verH = 0;
        //byte verL = 0;
        //ver=(verH<<8)|verL;
        //byte cmdLen = 0;    //cmdLen最小为1,最大为255.
        //byte cmdA = 0;
        //0x80 0b10000000   服务器角色,根服务器
        //0x40 0b01000000   MESH node角色
        //0x20 0b00100000   客户端角色
        //0x01 0b00000001   ACK应答
        //0x00 0b00000000   NACK非应答

        //byte textMsgEncode
        //tME=1 ASCII
        //tME=2 UTF8
        //System.Text.UTF8Encoding
        //tME=3 UNICODE
        //System.Text.Unicode
        //tME=3 GB2312
        //Encoding.GetEncoding("GB2312")
        //tME=3 GBK
        //Encoding.GetEncoding("GBK")
        //tME=3 GB18030
        //Encoding.GetEncoding("GB18030")
        //uint userid = 0;
        //byte uidA = 0;
        //byte uidB = 0;
        //byte uidC = 0;
        //byte uidD = 0;
        //userid=(uidD<<24)|(uidC<<16)|(uidB<<8)|uidA;
        public static bool CheckFlagRB(ref byte[] msg, int len)
        {
            //ASCII 'A' 0x41 65
            //ASCII 'B' 0x42 66
            if (msg[0] == 65 && msg[1] == 66)
                return true;
            else
                return false;
        }
        public static byte GetKey(ref byte[] msg, int len)
        {
            //byte keyA = 0;    //随机密钥
            //byte keyB = 0;    //包字节数量<=4096。一个byte最大只有255.
            byte keyA = msg[2];
            byte keyB = msg[3];
            if (keyB != len % 256)
                return 0;
            else
            {
                return (byte)(keyA ^ keyB);   //key=keyA^keyB;    //想用异或字节解密,一次一加密。
            }
        }
        public static int GetVersion(ref byte[] msg)
        {
            byte verH = msg[4];
            byte verL = msg[5];
            //ver=(verH<<8)|verL;
            return (verH << 8) | verL;
        }
    }

    private TcpListener tcpListener;
    private Thread listenThread;

    public SimpleTcpServer(string ipAddress, int port)
    {
        this.tcpListener = new TcpListener(System.Net.IPAddress.Parse(ipAddress), port);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        this.tcpListener.Start();

        while (true)
        {
            // 阻塞直到客户端连接  
            TcpClient client = this.tcpListener.AcceptTcpClient();

            // 创建一个新的线程来处理客户端通信  
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }



    /// <summary>
    /// 注意接受缓存只有4096字节。
    /// </summary>
    /// <param name="client"></param>
    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        GuestIP.RecordIpToDatabase(tcpClient);

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                // 阻塞直到客户端发送数据  
                bytesRead = clientStream.Read(message, 0, message.Length);

                if (bytesRead == 0)
                {
                    // 客户端关闭了连接  
                    break;
                }

                Console.WriteLine($"Read Bytes:{bytesRead}");
            }
            catch
            {
                // 客户端断开了连接  
                break;
            }


            //Check
            if (bRB.CheckFlagRB(ref message, bytesRead) == true && bytesRead > 4)
            {
                Console.WriteLine("RB应用来访");
                byte key = bRB.GetKey(ref message, bytesRead);
                Console.WriteLine("key:{0}", key);
                byte[] data = new byte[bytesRead - 4];
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (byte)(message[i + 4] ^ key);
                }
                //版本控制
                goto End;
            }


            // 将接收到的数据回显给客户端  
            ASCIIEncoding encoder = new ASCIIEncoding();
            string messageString = encoder.GetString(message, 0, bytesRead);
            Console.WriteLine("Received from client: " + messageString);

            byte[] buffer = encoder.GetBytes(messageString);

            // 发送回显数据给客户端  
            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();
        End:
            //查看来访IP信息
            GuestIP.ReadLastGuestIP();
        }

        tcpClient.Close();
    }
    static void Main(string[] args)
    {
        TcpServer server = new TcpServer("127.0.0.1", 8421);

        Console.WriteLine("TCP Server listening on port 8421...");

        // 阻止主线程结束,直到用户手动停止  
        Console.ReadLine();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Risehuxyc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值