1 var socket = ar.AsyncState as Socket; 2 3 //这就是客户端的Socket实例,我们后续可以将其保存起来 4 var client = socket.EndAccept(ar); 5 6 //判断是否是 webScoket 7 client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null, null); 8 string msg = Encoding.UTF8.GetString(buffer); 9 if (!msg.Contains("Sec-WebSocket-Key")) 10 return; 11 12 client.Send(PackageHandShakeData(buffer, buffer.Length)); 13 14 var timer = new System.Timers.Timer(); 15 timer.Interval = 2000D; 16 timer.Enabled = true; 17 timer.Elapsed += (o, a) => 18 { 19 //检测客户端Socket的状态 20 if (client.Connected) 21 { 22 try 23 { 24 if (client.Poll(10, System.Net.Sockets.SelectMode.SelectWrite)) 25 { 26 var data = Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()); 27 //var data = PackageHandShakeData(buffer, buffer.Length); 28 client.Send(data, data.Length, SocketFlags.None); 29 } 30 } 31 catch (SocketException ex) 32 { 33 Console.WriteLine(ex.Message); 34 } 35 } 36 else 37 { 38 timer.Stop(); 39 timer.Enabled = false; 40 Console.WriteLine("Client is disconnected, the timer is stop."); 41 } 42 }; 43 timer.Start(); 44 45 46 socket.BeginAccept(new AsyncCallback(ClientMsg), socket);
client.Send(PackageHandShakeData(buffer, buffer.Length));
这里已经握手成功了。
但是。
var data = Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()); //var data = PackageHandShakeData(buffer, buffer.Length); client.Send(data, data.Length, SocketFlags.None);
确一直发送失败。
请问 我稍作了哪一步?
看看这个:
http://blog.csdn.net/ceclar123/article/details/8791972
通肯定通。 握手都成功了。
@CallMeTommy: 抱歉,不小心点了反对,这不是我的本意
关注。
http://www.blue-zero.com/WebSocket/ 在线WebSocket测试,客户端完美兼容IE6及以上浏览器,服务端采用【C#.NET】异步socket开发,支持多客户同时在线,服务端发送数据长度不限。
缺少返回给客户端的HTTP请求握手
详细可参考:
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server
http://www.cnblogs.com/dolphinX/p/3462898.html