websocket 握手:开发人员需要为此做些什么吗?
我已经成功完成了 websocket 测试,但我想了解 Websocket 握手。在我的网络客户端中,我使用下面的代码来启动 websocket 通信
var ws = new WebSocket("ws://example.com/foobar");
ws.onmessage = function(evt) { /* some code */ }
ws.send("Hello World")
在我的网络服务器(使用 Java)中,我使用了 Jetty lib 并实现了如下所示的服务器:
public class MyWebSocket implements WebSocket.OnTextMessage {
public void onOpen(Connection connection)
{
}
public void onMessage(byte frame, byte[] data,int offset, int length)
{
}
public void onMessage(String data)
{
}
public void onClose(int code, String message)
{
}
}
Web套接字通信对我来说工作正常,我没有为握手做任何事情。它是如何运作的?
I have successfully completed my websocket test, but I want to know about Websocket handshake. In my web client I have used the below code to start websocket communication
var ws = new WebSocket("ws://example.com/foobar");
ws.onmessage = function(evt) { /* some code */ }
ws.send("Hello World")
In my web server (used Java) I have used Jetty lib and implemented server like below:
public class MyWebSocket implements WebSocket.OnTextMessage {
public void onOpen(Connection connection)
{
}
public void onMessage(byte frame, byte[] data,int offset, int length)
{
}
public void onMessage(String data)
{
}
public void onClose(int code, String message)
{
}
}
Web socket communication working fine for me, I have not done anything for handshake. How it is working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用像 Jetty 这样的库,诸如握手之类的重复操作是在幕后完成的,因此您不必处理这些事情。这就是使用库的想法 - 您可以编写直接的代码,而无需重新发明轮子。
如果您确实想自己实现握手,您可能想在没有库的情况下摆弄,并尝试如何“勉强”实现它。
对于Jetty,可以查看握手代码 这里,关键解析完成这里。
If you use a library like Jetty, repetitive things like handshaking is done behind the scenes so that you don't have to take care of that. That's the idea of using libraries - you can write straight-forward code without having to reinvent the wheel.
If you do want to implement handshaking yourself, you might want to fiddle around without a library and play around as to how to implement it "barely".
For Jetty, you can view the handshaking code here, and the key parsing is done here.