websocket - yii2 websocket 打开后立即关闭
问题描述
我有一个在 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 的最佳决定是什么?
PS编辑我的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。我不知道为什么。
解决方案
根据我的经验,SocketServer 在init()
客户端连接后立即崩溃。造成这种情况的一个原因是,如果您正在使用启动服务器,php-cli
那么崩溃的原因将是$user = User::findById(\Yii::$app->user->identity->id);
因为控制台应用程序没有用户身份组件,这会引发一个关闭服务器的异常。
推荐阅读
- batch-file - 我试图让一个 .exe 文件打开文件夹在哪里,
- javascript - 使用 Immutable.js 在 React 中访问数组中的对象
- tensorflow - 如何修复'ValueError:输入0与层simple_rnn_1不兼容:预期形状=(无,无,20),找到形状=(无,无,2,20)'
- dart - 我们如何将尺寸传递给 CustomPaint?
- python - 按原样单独获取 cookie - Python 请求
- java - 我应该在 if-else 块中抛出异常吗?
- postman - 邮递员:服务中断时如何断言情况
- html - 如何创建 div 的自定义 Notch?
- android - Google Drive REST API 是否仍需要 GET_ACCOUNTS 权限?
- r - Quantmod Heikin-Ashi 绘图不可用