gpt4 book ai didi

android - 无法从 android okhttp3 连接到 Node websocket

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:13 26 4
gpt4 key购买 nike

我在expressJs之上创建了一个 Node 服务器,并使用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}

出了什么问题?

最佳答案

尝试以下操作...看看是否有效。

 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();
}

Source

关于android - 无法从 android okhttp3 连接到 Node websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com