我有一个在yii2上工作的websocket应用程序。这是我的服务器端(使用https://github.com/consik/yii2-websocket):
class ChatServer extends WebSocketServer
{
public function init()
{
parent::init();
$this->on(self::EVENT_CLIENT_CONNECTED, function(WSClientEvent $e) {
$user = User::findById(\Yii::$app->user->identity->id);
$e->client->id = $user->id;
});
$this->on(self::EVENT_CLIENT_DISCONNECTED, function(WSClientEvent $e){
});
}
protected function getCommand(ConnectionInterface $from, $msg)
{
$request = json_decode($msg, true);
return !empty($request['action']) ? $request['action'] : parent::getCommand($from, $msg);
}
public function commandChat(ConnectionInterface $client, $msg)
{
$request = json_decode($msg);
$result = ['message' => ''];
if (!isset($request->recipient_id) || !isset($request->message)) {
$client->send(json_encode(['success' => false]));
}
$user = User::findById(\Yii::$app->user->identity->id);
if (!$user->isFriend($request->recipient_id)) {
$client->send(json_encode(['success' => false]));
}
$message = new Message();
$message->sender_id = $user->id;
$message->receiver_id = $request->receiver_id;
$message->text = $request->message;
if ($message->save())
{
$result['message'] = 'Sended.';
foreach($this->clients as $chatClient) {
if ($chatClient->id == $message->receiver_id) {
$chatClient->send( json_encode([
'type' => 'newMessage',
'message' => $message->text
]) );
}
}
}
else {
$result['message'] = 'Some error here.';
}
$client->send( json_encode($result) );
}
}
这是我的客户方:
$(function() {
var chat = new WebSocket('ws://localhost:8079/');
chat.onopen = function(e) {
console.log(e);
console.log('connected!');
};
chat.onclose = function(event) {
console.log('closed');
};
$('#btnSend').click(function() {
if ($('#message').val()) {
chat.send( JSON.stringify({'action' : 'chat', 'message' : $('#message').val()}) );
} else {
alert('Enter the message')
}
})
});
但是当我打开这个页面时,我在控制台中得到了这个:
connected!
closed
当我尝试通过chat.send
发送消息时,我得到了WebSocket is already in CLOSING or CLOSED state.
。
我该怎么办?为什么我的websocket关闭如此之快?
yii2上websockets的最佳决定是什么?
P.S。编辑我的js:
var chat = new WebSocket('ws://localhost:8080/');
chat._original_send_func = chat.send;
chat.send = function(data) {
if(this.readyState == 1) {
this._original_send_func(data);
}
else {
console.log('No')
}
}.bind(chat);
当我尝试发送消息时,readyState
不等于1.我不知道为什么。
答案 0 :(得分:0)
根据我的经验,在连接客户端之后,SocketServer在函数init()
中崩溃。这样做的一个原因是,如果您使用php-cli
启动服务器,那么崩溃的原因将是行$user = User::findById(\Yii::$app->user->identity->id);
,因为控制台应用程序没有用户身份组件,这会引发异常,从而关闭服务器