Android WebSocket,来自服务器的数据 [英] Android WebSocket, data from server

查看:43
本文介绍了Android WebSocket,来自服务器的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 WebSocket 服务器获得响应??网络服务器位于 http://www.websocket.org/echo.html

How can I get response from WebSocket server?? webserver is on the http://www.websocket.org/echo.html

推荐答案

您需要做的第一件事是知道如何连接并建立有效的 WebSocket 连接.这涉及连接、升级请求和握手以达成交易.(相对于在发送后关闭套接字的标准 HTTP GET 而言,保持套接字处于活动状态.然后您需要调用 echo url .. 参见这个主要示例..

The first thing you need to do is know how to connect and establish a valid WebSocket connection. This involves a connect, an upgrade request, and a handshake to seal the deal. (to keep the socket alive vs a standard HTTP GET that closes the socket after send. You then need to call the echo url.. See this main example..

/**
 * Quick echo test code.
 * @param args
 */
public static void main(String[] args) {
    try {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("key1", "value1");
        headers.put("key2", "value2");

        WebSocket ws = new WebSocket(new URI("ws://localhost:8080/echo"));
        ws.setHeaders(headers);
        ws.connect();

        String request = "Hello";
        ws.send(request);
        String response = ws.recv(); 
        System.out.println(request);
        if (request.equals(response)) {
            System.out.print("Success!");
        } else {
            System.out.print("Failed!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

关于如何操作的完整参考在这里 很好的例子

The complete reference on how to is here good example

我展示了从 Java 客户端的角度到 WebSocket 的回声的工作自包含类

I shows a working self contained class of an echo from a Java Client point of view to a WebSocket

这篇关于Android WebSocket,来自服务器的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆