Android デバイス ( https://www.mysms.comのようなもの) でブラウザーを SMS のエディターとして使用できるようにしたいと考えています。そこで、ソケットサーバーとして機能し、ブラウザをクライアントとして使用する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 エラーが発生しました: WebSocket ハンドシェイク中のエラー: 無効なステータス行
編集:
だから私は 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' ヘッダー値が正しくありません