我试图通过套接字连接 2 个设备,但它从来没有用过。其中一个设备是服务器,它将配置(IP 和监听的端口)保存在数据库上,然后另一个设备,客户端,与数据库连接并进行配置连接。
数据库查询和回显工作正常(PHP),但打开客户端套接字的方法不起作用,它没有时间连接并引发异常。我不知道是ServerSocket没有收到请愿还是ClientSocket没有发送...
下面的代码:(有点糟糕,但用于测试)。
服务器代码:
public class Server{
private int puerto = 4567;
private ServerSocket serverSocket;
public void conectar() {
try {
serverSocket = new ServerSocket(puerto);
while (true) {
Log.i("SocketServer", "escuchando");
Socket cliente = serverSocket.accept();
Log.i("Socket","Cliente ha conectado");
BufferedReader ent = new BufferedReader(new InputStreamReader(
cliente.getInputStream()));
String linea = ent.readLine();
Log.i("Cliente", "Cliente envia=" + linea);
cliente.close();
Log.i("Servidor","Cliente desconectado");
}
} catch (IOException e) {
Log.e("Error", "Error en el servidor");
}
}
客户端代码:
public class Cliente {
private int puerto;
private InetAddress direccion;
public Cliente(int puerto, InetAddress direccion){
this.puerto = puerto;
this.direccion = direccion;
}
public void conectar(){
try{
Socket cliente = new Socket(direccion, puerto);
Log.i("Cliente", "Conectado");
conectado = true;
PrintWriter salida=new PrintWriter(cliente.getOutputStream(),true);
salida.println("Hola, soy el cliente");
Log.i("Cliente", "Mensaje enviado");
cliente.close();
}catch(SocketException e){
Log.e("ErrorSocket","Error al abrir socket " + e.getMessage());
} catch (IOException e) {
Log.e("ErrorSocket","Error al enviar " + e.getMessage());
}
}
}
我通过以下方法获得 InetAddress:
//The String result param is like: "192.168.0.1&23456"
public InetAddress getInetAddress(String result) {
InetAddress address = null;
//5 it an example
if (result.length() > 5 && result != null) {
try {
String[] data = result.split("&");
Log.i("Data", data[0] + " " + data[1]);
puerto = Integer.parseInt(data[1]);
Log.i("PUERTO", "Puerto:" + puerto);
String ip = data[0];
Log.i("IP", ip);
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
address = InetAddress.getByAddress(IP);
Log.i("InetAddress",address.getCanonicalHostName());
} catch (Exception e) {
Log.e("Error", "Error al conseguir InnetAddress");
}
} else {
Log.e("Error", "String capturado vacio");
return address;
}
return address;
}
谢谢 :) 这是我的大学期末项目的一个测试项目,一个 GPS 聊天。
编辑:3G nat 打破了这种方式,通过套接字在 2 个设备之间建立 android 连接。我将研究使用 GCM 和另一台服务器的方法。