我使用下面的代码连接到一个php websocket。
serverAddr = InetAddress.getByName(ip_str);
socket = new Socket(serverAddr, port_str);
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));尝试打开套接字,并希望侦听来自服务器的数据。
ip_str是这样的:wss://xyz.com: 8181 / port,其中xyz是实际的主机名,8181是一个虚拟端口号(在这里我无法给出实际值时给出了虚拟值--但它在web上运行得很好,因为我们试图通过web连接相同的套接字)。
在这条线上:
socket = new Socket(serverAddr, port_str);我收到以下错误消息:
java.net.ConnectException: failed to connect to ip6-localhost/::1 (port 8181): connect failed: ECONNREFUSED (Connection refused)有人知道我为什么要面对这个问题吗?
发布于 2017-09-07 00:23:53
如果ip_str是像"wss://xyz.com:8181/game"这样的完整URL,那么下面一行是完全错误的:
serverAddr = InetAddress.getByName(ip_str);您不能将URL传递给InetAddress.getByName()。它只接受虚线IP地址或主机名作为输入,例如:
serverAddr = InetAddress.getByName("xyz.com");因此,使用URI或URL类将URL解析为其组成组件,然后您可以将主机名组件解析为IP地址,例如:
URI WebSocketUri = new URI("wss://xyz.com:8181/game"); // or URL
serverAddr = InetAddress.getByName(WebSocketUri.getHost());
...或者,您可以让Socket为您解析主机:
URI WebSocketUri = new URI("wss://xyz.com:8181/game"); // or URL
if (WebSocket.getScheme() == "wss")
socket = new SSLSocket(WebSocket.getHost(), WebSocket.getPort());
else
socket = new Socket(WebSocket.getHost(), WebSocket.getPort());
// send an HTTP request for WebSocket.getRawPath() and negotiate WebSocket handshake as needed...或者更好的方法是使用URLConnection:
WebSocketUri = new URL("wss://xyz.com:8181/game");
URLConnection conn = WebSocketUri.openConnection();
...或者,使用一个实际的第三方WebSocket库(其中有许多可供安卓使用)。
发布于 2017-09-06 13:46:53
这是因为您正试图通过安全/加密的连接( wss:// )进行连接。在应用程序能够连接到目标地址之前,您需要额外的步骤。通常是先设置证书。
您可以检查此解决方案:Unable to connect websocket with wss in android。这里有更多信息:how to create Socket connection in Android?
https://stackoverflow.com/questions/46074809
复制相似问题