其他分享
首页 > 其他分享> > SocketHelper

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;
        }

    }

 

标签:stream,buffer,SocketHelper,new,byte,public,messageData
来源: https://www.cnblogs.com/shuajing/p/11658392.html