我正在写一个websockets-client。我有两个问题:
当我关闭应用程序的窗口时,服务器会关闭
服务器未接收消息,但客户端始终收到来自服务器的问候消息。
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();
}
}
永久性说&#34;连接&#34;。
答案 0 :(得分:1)
我怀疑这可能是握手时的错误 - 当我看到代码时,我看到如果没有握手,则会抛出此错误
private bool EnsureWebSocketOpen()
{
if (!Handshaked)
{
OnError(new Exception(m_NotOpenSendingMessage));
return false;
}
return true;
}