【发布时间】:2014-01-04 00:32:28
【问题描述】:
所以,我正在尝试解析一个使用 websocket 向客户端发送数据的网站。根据我的阅读:
我知道为了创建一个连接,我需要向服务器发送一个特殊的 http 请求,然后会检索一些我用来访问通道的数据。
我做了什么:
-
创建了 http 请求
`URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("Cache-Control", "no-cache"); con.setRequestProperty("Host", "www.example.com"); con.setRequestProperty("Upgrade", "websocket"); con.setRequestProperty("Connection", "upgrade"); con.setRequestProperty("Origin", "https://example.com"); con.setRequestProperty("Sec-WebSocket-Extensions", "x-webkit-deflate-frame"); con.setRequestProperty("Sec-WebSocket-Key", "QkWkChtTGpaZL5PkOMaRtg=="); con.setRequestProperty("Sec-WebSocket-Version", "13"); con.setRequestProperty("User-Agent", "Mozilla/..;`
我阅读了带有代码 200 的响应(不是应该的 101)。
问题:
- 如何生成Sec-Websocket-Key? (示例取自萤火虫,实际上所有标题)
1.1。还有什么可以做的?
1.2。必须使用来自 http 的相同链接来访问 websocket?仅使用 wss 而不是 https?
-
在此之后,我尝试将客户端连接到服务器并在 onMessage 方法中接收消息。
WebSocketContainer container = ContainerProvider.getWebSocketContainer(); Session session = container.connectToServer(ClientEndpoint.class, buildCEC(), new URI("wss://async.example.com/socket.io/1/?t=" + System.currentTimeMillis())); -
我尝试在 buildCec() 中插入标头以连接到服务器。
ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build(); Configurator conf = config.getConfigurator();`Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Connection", Arrays.asList("keep-alive", "Upgrade")); headers.put("Sec-Websocket-Extensions", Arrays.asList("x-webkit-deflate-frame")); headers.put("Sec-Websocket-key", Arrays.asList("cx36sHrtuW9HZAaB6kKa/Q==")); headers.put("Sec-Websocket-Version", Arrays.asList("13")); headers.put("Upgrade", Arrays.asList("websocket")); headers.put("User-Agent", Arrays.asList("Mozill...")); conf.beforeRequest(headers); return config;`
问题
- 如果我解决并收到来自 http 升级请求的 101 状态代码,我的判断是否正确?(我的意思是,我接下来如何处理这些细节?)
- 请不要评判我,我刚开始使用java中的websockets,我不太了解javascript,我想用jsr-356在纯java中做这个客户端。我已经用 websockets 做了一些小例子,但是我在任何地方都找不到一个好的客户端,带有标头和更复杂的握手。
- 是否可以连接到未知服务器,但不知道所有详细信息?
我正在使用编程端点并导入 javax.websocket.ContainerProvider;用于处理来自 jsr356 的 websocket 连接。
【问题讨论】:
-
我认为使用一些客户端库会更容易。一些谷歌搜索:eclipse.org/jetty/documentation/current/…
-
我想了解他们创建 websockets 概念的基础知识,首先,然后使用库。反正我去看看。
-
将来,您可能希望将这些多主题的问题拆分为单独的问题。