private void MainForm_Load(object sender, EventArgs e) { string strip = Dns.GetHostAddresses("openbarrage.douyutv.com")[0].ToString(); strdatetime = GetTimeStamp(); Socket clientSocket; IPAddress ip = IPAddress.Parse(strip); clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); string roomid = "3567314";//"288016";//test try { clientSocket.ReceiveTimeout = 1000000; clientSocket.Connect(new IPEndPoint(ip, 8601)); if (clientSocket.Connected) { Console.WriteLine("已与弹幕服务器建立连接"); } MsgBody loginreq = new MsgBody("type@=loginreq/roomid@=" + roomid + "/" + "ver@=20190530/ct@=0");//最后添加的字符串是在2019.5各大视频平台弹幕整改的情况下,使本弹幕接口仍然能够获取到弹幕消息 //MsgBody send = new MsgBody("type@=joingroup/rid@=" + "22222" + "/gid@=-9999/"); byte[] msg = loginreq.toByte(); //byte[] join = send.toByte(); clientSocket.Send(msg); //Thread.Sleep(500); MsgBody send = new MsgBody("type@=joingroup/rid@=" + roomid + "/gid@=-9999/"); byte[] join = send.toByte(); clientSocket.Send(join); //clientSocket.Send(join); //Console.WriteLine("消息长度为:" + msg.Length); //Console.WriteLine("消息长度为:" + join.Length); } catch (Exception ex) { Console.WriteLine("连接服务器失败,请按回车键退出!"); return; } //RecvMsg(clientSocket); Thread threadRecvMsg = new Thread(RecvMsg); threadRecvMsg.IsBackground = true; threadRecvMsg.Start(clientSocket); Thread threadSendHeartBeat = new Thread(SendHeartBeat); threadSendHeartBeat.IsBackground = true; threadSendHeartBeat.Start(clientSocket);/* * Thread threadUpdate = new Thread(updateText); * threadUpdate.IsBackground = true; * threadUpdate.Start();*/ }
/// <summary> /// 每隔45s发送心跳消息 /// </summary> static void SendHeartBeat(object socket) { while (true) { Socket clientsocket = (Socket)socket; MsgBody body = new MsgBody("type@=mrkl/"); byte[] msg = body.toByte(); clientsocket.Send(msg); Thread.Sleep(15000); //MessageBox.Show("" + clientsocket.Connected.ToString()); } }