Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

websocket onopen onmessage opclose 回调函数,增加用户数据void* #540

Closed
xinsuinizhuan opened this issue May 8, 2024 · 9 comments

Comments

@xinsuinizhuan
Copy link

websocket服务端,三个回调函数,都增加第三个参数:用户数据
图片

图片

这样,我初始化server.registerWebSocketService(&ws);的时候,就可以把所谓的上下文添加到回调函数中,回调函数返回时,直接返回对应的用户数据,也就是上下文

同理,客户端也是

@xinsuinizhuan
Copy link
Author

另外,咨询一下,websocket 客户端,这个headers["Origin"] 是什么意思,headers["Origin"] = "http://example.com/"; 我不填或者写个其他,可以吗?

@ithewei
Copy link
Owner

ithewei commented May 8, 2024

std::function可以bind任意的参数,所以不必要像纯c回调函数一样需要添加userdata,你可以使用ws.onopen = [userdata](...)去捕获参数列表

@ithewei
Copy link
Owner

ithewei commented May 8, 2024

headers["Origin"]这个头部可以设置成自己的域名,如果服务端不验证这个头部字段,你也可以不填

@xinsuinizhuan
Copy link
Author

std::function可以bind任意的参数,所以不必要像纯c回调函数一样需要添加userdata,你可以使用ws.onopen = [userdata](...)去捕获参数列表

你说的绑定怎么绑定? auto ctx = channel->newContextPtr(); 这样?

@xinsuinizhuan
Copy link
Author

xinsuinizhuan commented May 9, 2024

只所以要做用户数据,是因为我一开始设置回调函数时,我就设置了用户数据,您example里面的绑定上下文已经是onopen回调函数里面,来给channel绑定上下文,并且绑定一般都是绑定创建他或者他本身的类指针:
图片

已经到了回调函数里面了,再去绑定,那类指针都找不到了,并且并非要像websocket_server_test.cpp里面,已经到了onopen回调函数了,再去创建一个类指针,给它做绑定,要绑定的是原始或者回调函数本身拥有者的类指针

@xinsuinizhuan
Copy link
Author

headers["Origin"]这个头部可以设置成自己的域名,如果服务端不验证这个头部字段,你也可以不填

那在服务器里面,怎么获取到这个字段,我看websocket_server_test.cpp里面,没有相关的验证这个头的东西?

@ithewei
Copy link
Owner

ithewei commented May 9, 2024

建议你先学习下c++11 lambda函数吧,lambda可以捕获任何参数,包括this指针,这里有示例代码

onopen = [this]() {

@ithewei
Copy link
Owner

ithewei commented May 9, 2024

headers["Origin"]这个头部可以设置成自己的域名,如果服务端不验证这个头部字段,你也可以不填

那在服务器里面,怎么获取到这个字段,我看websocket_server_test.cpp里面,没有相关的验证这个头的东西?

可以通过req->headers["Origin"]获取这个字端,websocket_server_test.cpp并没有去验证,一些三方的websocket服务可能会验证,如果不验证,你不设置就好了

@xinsuinizhuan
Copy link
Author

建议你先学习下c++11 lambda函数吧,lambda可以捕获任何参数,包括this指针,这里有示例代码

onopen = [this]() {

好的。懂了,谢谢。

@ithewei ithewei closed this as completed May 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants