使用Android作为服务器和浏览器作为客户端创建WebSocket握手

4
我希望能够在我的Android设备上使用浏览器作为短信编辑器(类似于https://www.mysms.com)。因此,我开始编写一个Android应用程序,它充当套接字服务器,并使用浏览器作为客户端(例如http://www.websocket.org/echo.html)。我能够从该客户端访问我的应用程序并获取消息,但现在我遇到了WebSocket握手(Sec-WebSocket-Key等)的问题。
编辑:
我按照这个教程编写了我的Android服务器:http://android-er.blogspot.co.at/2014/02/android-sercerclient-example-server.html。当我尝试从http://www.websocket.org/echo.html访问该服务器时,我得到了这个js错误:Error during WebSocket handshake: Invalid status line。
编辑:
因此,我添加了编码密钥的标题以获取Sec-WebSocket-Accept:行。
// get the key from the input 
InputStream inputStream = hostThreadSocket.getInputStream();
            String line = "";
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(inputStream));
                while ((line = reader.readLine()) != null) {
                    if(line.contains("Sec-WebSocket-Key:")){ // stop then the line containing the key is found
                        break;
                    }
                }

            } catch (IOException e) {
            }
String key = line.replace("Sec-WebSocket-Key:", "");

并使用以下方法对结果进行编码:
static String encodeString(String input)  {

    MessageDigest digest = null;
    try {
        digest = MessageDigest.getInstance("SHA-1");
        byte[] inputBytes = input.getBytes();
        byte[] hashBytes = digest.digest(inputBytes);
        return  Base64.encodeToString(hashBytes, Base64.DEFAULT);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

并像下面一样传递头文件:
 String key = line.replace("Sec-WebSocket-Key:", "");
            key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            key = encodeString(key).replace("\n", "");;

            String header = "HTTP/1.1 101 Switching Protocols\r\n" +
                    "Upgrade: websocket \r\n" +
                    "Connection: Upgrade \r\n" +
                    "Sec-WebSocket-Accept: " + key + "\r\n"+
                    "Sec-WebSocket-Protocol: chat\r\n\r\n" + msgReply;
            printStream.print(header);
            printStream.close();

响应头现在的样子如下:
Connection:Upgrade\r\n 
Sec-WebSocket-Accept:/Qg4DR68UCCo9VKy4vbDgswCU8Y=\r\n
Upgrade:websocket\r\n

但我仍然收到错误消息: 失败:WebSocket握手期间出现错误:'Sec-WebSocket-Accept'标头值不正确。

握手协议有什么问题吗?你能提供一下你所收到的HTTP请求和响应的例子吗? - vtortola
我更新了我的问题并提供了更具体的信息。 - richard
2个回答

4

我最终成功进行了WebSocket握手。我不知道是什么变化使我取得了成功,但这是可行的代码:

InputStream inputStream = hostThreadSocket.getInputStream();
            String line = "";
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(inputStream));
                while ((line = reader.readLine()) != null) {
                    if (line.contains("Sec-WebSocket-Key: ")) { // check if its the header-line containing the websocket key
                        break;
                    }
                }
            } catch (IOException e) {
                Log.e(TAG_TEST, e.getMessage(), e);
            }

            Matcher matcher = pattern.matcher(line); // with pattern "Sec-WebSocket-Key:[ ]*([^\r^\n]*)" to parse the key out of the line
            boolean matches = matcher.matches();
            String key = matcher.group(1);
            key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // adding the "magic string"
            key = encodeString(key);

            String header = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" +                       
                    "Upgrade: websocket\r\n" +
                    "Connection: Upgrade\r\n" +
                    "Sec-WebSocket-Accept:" + key + "\r\n\r\n";
            printStream.print(header);

这是加密密钥的编码方法:

static String encodeString(String input) {
    MessageDigest digest = null;
    try {
        digest = MessageDigest.getInstance("SHA-1");
        byte[] inputBytes = input.getBytes();
        byte[] hashBytes = digest.digest(inputBytes);
        return Base64.encodeToString(hashBytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG_TEST, e.getMessage(), e);
    }
    return "";
}

非常感謝提供解決方案, 對我幫助很大。 - charliebeckwith

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接