我创建了一个客户端和一个服务器,它们都可以正常工作并且没有连接问题。现在我希望能够从我的Android手机连接到服务器。我导入了kryonet库并将客户端代码复制粘贴到一个新的android项目中。代码给了我一些错误,但我修复了这些错误。当我尝试测试我的应用时,它没有给我任何错误,但我的服务器也没有得到任何连接。我在LogCat日志中看了一下,发现它一直坚持着#34;正在连接.."。我完全陷入困境。这是我的android代码:
public void openSocket(View view){
Log.i(TAG, "test1");
EditText portText= (EditText)findViewById(R.id.port);
String parts[] = portText.getText().toString().split(":");
partIP = parts[0];
String partPort = parts[1];
port = Integer.parseInt(partPort);
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
connect();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = "Android";
client.sendTCP(packet);
}
这是我正常的客户代码:
public static void main(String[] args) {
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
new Main();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public Main() {
try {
connect();
Thread t = new Thread(this);
t.start();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = System.getProperty("user.name");
client.sendTCP(packet);
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(3000);
if (!client.isConnected())
connect();
} catch (InterruptedException e) {
pHandler.checkException(e);
}
}
}
}
所以这个:
client.connect(5000, ipFinal, port, port);
是它在Android上遇到的线路。普通客户端只是正常连接。
现在我的问题是,我的Android代码有问题,还是只是设备或wifi连接?
如果它有帮助,我尝试在我的三星Galaxy nexus上进行测试,这是根深蒂固的。
提前致谢。