简体   繁体   English

客户端-服务器程序,可以从Java客户端连接,但不能从Android连接

[英]Client-Server Program, can connect from Java client but not from Android

I have a working Java client/server program which is very straightforward and basic. 我有一个工作的Java客户端/服务器程序,该程序非常简单和基本。 This works fine. 这很好。 However, I am now trying to write an Android client, and I have been unable to connect to the server from my android client. 但是,我现在正尝试编写一个Android客户端,但无法从android客户端连接到服务器。 I am using almost identical code for the android networking code as I use for the normal client. 我为Android联网代码使用的代码几乎与普通客户端使用的代码相同。 My android code is simple, all it does is starts this thread from onCreate: 我的android代码很简单,它所做的就是从onCreate启动此线程:

private int serverPort = 8889;
private String serverIP = "192.168.5.230";
private Socket socket = null;

private Thread clientThread = new Thread("ClientThread") {
    @Override
    public void run() {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(serverIP, serverPort), 1000);
            DataInputStream din = new DataInputStream( socket.getInputStream());
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());

            while (true) {
                String message = din.readUTF();
                setPicture("picture1");
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
};

The port is the correct port my server is running on, as is the ip address (which I got from ifconfig since I know you cannot use localhost). 该端口是服务器运行的正确端口,也是IP地址(我从ifconfig获得的IP地址,因为我知道您不能使用localhost)。 When I run my normal pc client with the same port and IP address, the connection goes through. 当我使用相同的端口和IP地址运行普通的PC客户端时,连接将通过。 But when I run this code on my android device, the socket timesout when I try to connect. 但是,当我在Android设备上运行此代码时,尝试连接时套接字超时。

Does anyone have any suggestions for where I am going wrong? 有人对我要去哪里有什么建议吗?

Double check that you added the permission requirement in the manifest file: 仔细检查您是否在清单文件中添加了权限要求:

<uses-permission android:name="android.permission.INTERNET" />

But, possibly more importantly, 192.168.xx is a local or non-routable network so you need to be on the same network, or one that knows how to reach the 192.168.5.230 address. 但是,可能更重要的是,192.168.xx是本地或不可路由的网络,因此您需要位于同一网络上,或者是知道如何访问192.168.5.230地址的网络。 You say that it doesn't work when you try it on your device -- are you running on local wifi when you run or are you on your mobile network? 您说在设备上尝试时不起作用-运行时是在本地wifi上运行还是在移动网络上? If you're on mobile, try it from wifi. 如果您在移动设备上,请通过wifi尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM