我收到 java.net.ConnectException: /ip_address:port - Connection denied 异常。
这是代码:
public boolean sendMessage(String message, String ip, int port)
{
try {
Log.i("Log", "Socket Operator IP before split : "+ip);
String[] str = ip.split("\\.");
for(int i =0;i<str.length;i++)
{
Log.i("Log", "Socket Operator after split : "+str[i]);
}
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
Log.i("Log","Socket Operator SOCKET got null");
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (UnknownHostException e) {
Log.i("Log","Socket Operator SOCKET got UnknownHostException");
return false;
//e.printStackTrace();
} catch (IOException e) {
Log.i("Log","Socket Operator SOCKET got IOException");
e.printStackTrace();
return false;
//e.printStackTrace();
}
Log.i("Log","Socket Operator SOCKET got executed");
return true;
}
这是我的 getSocket 方法:
private Socket getSocket(InetAddress addr, int portNo)
{
Log.i("Log","Socket Operator InetAddress : "+addr.toString()+" Port : "+portNo);
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
Log.i("Log","Socket Operator socket is true");
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
Log.i("Log","Socket Operator socket is false");
try {
Log.i("Log","Socket Operator socket is false in try start");
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
我已经关注了这些链接,但没有运气:
1 https://stackoverflow.com/a/6876306/1395259
2 java.net.ConnectException - 连接被拒绝 Android 模拟器
请帮我解决这个问题。
提前致谢。