我在expressJs上创建了一个节点服务器,并使用socket.io创建了一个websocket服务器。用于创建服务器的代码是
io.sockets.on('connection', function (socket) {
connections.push(socket);
console.log('Connected: ' + connections.length + 'sockets connected');
io.sockets.emit('connected', JSON.stringify({status: "online"}));
socket.on('disconnect', function (data) {
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: ' + connections.length + ' sockets connected');
io.sockets.emit('disconnected', {status: "offline"});
});
socket.on('request', function (data) {
console.log('new request in server: ' + data.toString());
io.sockets.emit('newRequest', JSON.stringify({request: data}));
})
});
我可以从任何浏览器连接服务器,包括移动和模拟器浏览器,但我无法使用okhttp3 websocket连接。
我正在关注https://gist.github.com/AliYusuf95/557af8be5f360c95fdf029795291eddb这个要点来创建客户端。但我没有连接websocket。我收到以下错误
D/OkHttp: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on Connection{192.***.0.***:3000, proxy=DIRECT@ hostAddress=/192.***.0.***:3000:3000 cipherSuite=none protocol=http/1.1}
出了什么问题?
答案 0 :(得分:0)
请尝试以下操作...看看是否有效。
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://websockethost:8080");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.messages);
textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}