我正在编写一个websockets客户端。我有两个问题:
-
当我关闭应用程序的窗口时,服务器会关闭
-
服务器未接收到消息,但客户端始终从服务器接收问候消息。
System.Exception:必须在websocket为之后通过websocket发送数据打开
客户端在C#(Websocket4Net-lib)上
private static void _clientSocket_Closed(object sender, EventArgs e)
{
if (_clientSocket.State == WebSocket4Net.WebSocketState.Open)
{
_clientSocket.Close("Closed by user");
}
}
public static void WebRequest(string url, dutyObject objToSend)
{
_clientSocket = new WebSocket(url);
_clientSocket.MessageReceived += _clientSocket_MessageReceived;
_clientSocket.DataReceived += _clientSocket_DataReceived;
_clientSocket.Closed += _clientSocket_Closed;
_clientSocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(_clientSocket_Error);
_clientSocket.Open();
var jsonMessage = JsonSerializeHelper.Serialize(objToSend);
_clientSocket.Send(jsonMessage);
}
php 上的服务器
class Server extends WebSocketServer
{
protected function serverCreated()
{
}
/**
* This is run when server is receiving data.
*/
protected function process($connected_user, $message)
{
$this->send($connected_user,"[+]".$message); //just echo reply
}
/**
* This is run when socket connection is established. Send a greeting message
*/
protected function connected($connected_user)
{
$welcome_message = 'Welcome to Service. Service works with JSON. Be careful!';
$this->send($connected_user, $welcome_message);
}
protected function closed($connected_user)
{
$this->stdout("User closed connection n");
}
}
客户端上的更新。
while (_clientSocket.State != WebSocketState.Open)
{
if (_clientSocket.State == WebSocket4Net.WebSocketState.Open)
{
Console.WriteLine(_clientSocket.State);
_clientSocket.Send(ecn.GetBytes(jsonMessage), 0, ecn.GetBytes(jsonMessage).Length);
}
else
{
Console.WriteLine("E: " + _clientSocket.State);
//_clientSocket.Close();
}
}
它永久地写着"连接"。
我怀疑这可能是握手时的错误-当查看代码时,我发现如果没有握手,则会抛出
private bool EnsureWebSocketOpen()
{
if (!Handshaked)
{
OnError(new Exception(m_NotOpenSendingMessage));
return false;
}
return true;
}