Laravel-swoole: 关于OnMessage的触发机制

Created on 2 May 2018  ·  11Comments  ·  Source: swooletw/laravel-swoole

一直无法调用onMessage 看了源码才知道有个eventExists的判断
请问下event在哪配置?

help wanted question

Most helpful comment

@albertcht 算不上是CORS的问题, socket io默认会把protocol强行转换为当前页面的protocol,在config添加 transport完美解决问题

io = io(url, {transports: ['websocket']})

感谢你提供的链接,解决方案从那儿的源代码中获取。

All 11 comments

Hi @junshenshi ,

請參考 https://github.com/swooletw/laravel-swoole/wiki/7.-Websocket 這邊類似 Route 的註冊方式,可以用 Closure 或是 Handler 的方式來註冊 event

如果是使用現在新版的 master release,若不是使用預設的 socket.io 協議還須自己實作 Parser 來解析 encode 和 decode 方法

OK 好了 谢谢!

你好,刚刚测试发送,
Websocket::emit('message', '111111111111111111111111');
客户端能响应,但是 event.data为空。。。

請問是使用預設的 socket.io handler 嗎?還是自己實作的?

OK了 刚刚实现了Parser,但不清楚为什么要这样子设计,
使用自身handler需要改变parser。。
个人建议是不是应该先在OnMessage检测解释器是否存在?没有的话默认原样输出,就不需要预设socket.io handler

parser 的設計是為了規範出傳輸資料中 event 和 data 的部分,這樣在 onMessage 中才能使用這個套件 websocket 封裝好的 event callback 機制來分派處理邏輯
當開發者自己實作 handler 來傳輸資料時,也一定會自己定義資料格式,所以 parser 應該能幫助提供實作的規範和地方
另外其實 package 預設使用 socket.io handler 也是希望開發者不需要自己再自訂傳輸格式,客戶端也可以使用現成的 socket.io client 來與 server 溝通,開發者只要專注在對應 event 的邏輯處理就好了

@albertcht 应该怎么使用socket io client 来连接websocket呢?我在browser console试了试还是不行。

window.io = require('socket.io-client')

let io = io("wss://localhost:1215")

错误返回

Failed to load https://localhost:1215/socket.io/?EIO=3&transport=polling&t=MDG6yVb: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://locahost' is therefore not allowed access. The response had HTTP status code 500.

Hi @LostNCG ,

看起來只是 CORS 的問題,利用線上工具測試看看能不能連線?http://amritb.github.io/socketio-client-tool/ 他預設直接 ws 連線,不經過第一發 socket.io upgrade 的 http 連線

@albertcht 算不上是CORS的问题, socket io默认会把protocol强行转换为当前页面的protocol,在config添加 transport完美解决问题

io = io(url, {transports: ['websocket']})

感谢你提供的链接,解决方案从那儿的源代码中获取。

可以移除 cors,跨域的问题可以交给NGINX处理,虽然麻烦一点,但是会更快,只需要加入下面的配置就好了
add_header Access-Control-Allow-Origin "*"; add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS"; if ($request_method = OPTIONS ) { return 200; }

@junshenshi @albertcht 能贴一下代码吗?怎么解决这个?我不是很清楚

Was this page helpful?
0 / 5 - 0 ratings