SocketHelper

1.socket客户端调用

public class SocketHelper
    {
        public string IP { get; set; } = Constant.SSL_SOCKET_HOST;

        public int Port { get; set; } = int.Parse(Constant.SSL_SOCKET_PORT);

        public string BodyMessage { get; set; }

        public string MethodCode { get; set; }


        public string RunClient()
        {


            byte[] messsage = Encoding.UTF8.GetBytes(BodyMessage);

            var client = new TcpClient(IP, Port);
            var stream = client.GetStream();

            //写数据
            stream.Write(messsage, 0, messsage.Length);
            stream.Flush();

            //读数据
            List<byte> byteList = new List<byte>();

            byte[] buffer = new byte[2048];
            while (true)
            {
                int count = stream.Read(buffer, 0, buffer.Length);
                if (count < 2048)
                {
                    byte[] lastBuffer = new byte[count];
                    lastBuffer = buffer.Skip(0).Take(count).ToArray();
                    byteList.AddRange(lastBuffer);
                    break;
                }
                byteList.AddRange(buffer);
                buffer = new byte[2048];

                Thread.Sleep(10);//CPU处理数据到缓冲区
            }

            stream.Close();
            client.Close();

            var messageData = Encoding.UTF8.GetString(byteList.ToArray());
            if (!string.IsNullOrEmpty(messageData))
                messageData = messageData.Replace("/**/", "\"");
            return messageData;
        }

    }

 

上一篇:Cordova-在现有iOS工程自动化接入Cordova插件


下一篇:javascript – 带位置服务的wkwebview