C#笔记(9)Socket长连接

来源:互联网 发布:西北师大知行学院分布 编辑:程序博客网 时间:2024/06/03 04:00

新建类SocketIO.cs

class SocketIO    {        public static Socket client;        public static Thread thread;        public static IPAddress ip = new IPAddress(new byte[] {IP号, IP号, IP号, IP号 });        public static IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(端口号));        public static System.Windows.Forms.Timer heartBeat;        public static void startSocket()        {            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            client.Connect(point);            thread = new Thread(new ThreadStart(ReceiveMsg));            thread.IsBackground = true;            thread.Start();        }        public static void ReceiveMsg()        {            while (true)            {                byte[] buffer = new byte[1024 * 1024];                if (client.Receive(buffer) != 0)                {                    String json = Encoding.UTF8.GetString(buffer);//将byte转换成String                    json=json.Replace("\0", "");//去掉多余的\0                    //接收数据后做的事情                }            }        }        public static void SendMsg(String msg)        {            //客户端给服务器发消息            if (client != null)            {                byte[] buffer = Encoding.UTF8.GetBytes(msg);                client.Send(buffer);            }        }    }