我现在正面临这个问题。
我能够向设备发送命令并从设备接收到从android模拟器到套接字的响应。
但是,当我在平板电脑上安装相同的应用程序时,会出现问题。我第一次发送命令来检查设备是否已连接状态,它会向我发送设备已连接的响应,但是当我第二次发送命令时,它会抛出以下异常:
java.net.ConnectException:/192.168.1.106:8002 - 拒绝连接。
这是执行请求的代码:
public static String sendRequestandResponse(final String host,final int port,
final String command,
final int timeoutInMillis,final int responseLength) throws UnknownHostException,NetworkSettingException
{
if (host == null)
{
throw new NullPointerException("host is null"); //NOPMD
}
Socket clientSocket=null;
try {
/**
* Creating socket connection with IP address and port number to send Command
*/
try{
clientSocket = new Socket();
SocketAddress remoteAdr = new InetSocketAddress(host, port);
clientSocket.connect(remoteAdr, 1000);
clientSocket.setSoTimeout(timeoutInMillis);
}catch (Exception e) {
e.printStackTrace();
throw new NetworkSettingException(e.getMessage());
}
final PrintWriter outPutStream = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), CHARSET));
try
{
outPutStream.print(command);
outPutStream.flush();
BufferedReader responseString = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), CHARSET));
response = new StringBuilder();
try
{
int pos = 0;
while (true)
{
pos++;
System.out.println(pos);
int i=responseString.read();
byte[] resp={(byte)i};
System.out.println(new String(resp));
response.append(new String(resp));
if(pos>=responseLength){
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Log.d("ConnectionSocket", "Socket closed with break");
break;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
finally
{
responseString.close();
}
}
finally
{
outPutStream.close();
}
}
catch(IOException ex){
}
catch(NullPointerException ex){ //NOPMD
}
finally
{
try {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
} catch (NullPointerException ex) { //NOPMD
} catch (IOException ex) {
}
}
return response.toString();
}
我认为它第一次没有关闭套接字,所以第二次拒绝连接。
相同的代码可以在模拟器上运行。
答案 0 :(得分:0)
只有在服务器不接受连接时才会拒绝连接。
大多数情况下,问题是阻止任何不受信任的传入连接的防火墙。
我的应用程序主要在服务器有阻止它的防火墙时显示此消息。
因此,您可以在防火墙中为您的应用程序添加例外列表。