无法通过套接字从java向模拟器发送数据

时间:2016-03-21 11:09:09

标签: java android sockets android-emulator

我在android中运行一个服务,我有一个(服务器)套接字,它监听端口5587.I有一个java(客户端)套接字程序,必须将数据发送到android模拟器。但它不能发送数据到我给了(服务器)即android模拟器的ip地址为10.0.2.15.I也尝试了10.0.0.3,10.0.0.4,10.0.0.5,10.0.0.6.But(客户端)java cant send data..it显示“连接超时”。如果我给手机的IP地址并在手机上运行,​​我的代码工作正常。我猜IP地址或端口号是错误的。

我的java程序:

public class Main {
public static void main(String[] args) {
    System.out.println("enter data to send to android");
    mess = sc.nextLine();

    try {

            client = new Socket("10.0.2.15", 5587);
            // emulator ip
            oos = new ObjectOutputStream(client.getOutputStream());
            oos.writeObject(mess);
            ois = new ObjectInputStream(client.getInputStream());
            message = (String) ois.readObject();
            System.out.println("Message: " + message);
            if(message == "Received"){

                 System.out.println("Message Sent Sucessfully");

            }
            else{
                System.out.println("Message Not Sent...Try to resend");
            }
            //close resources
            ois.close();
            oos.close();
            client.close();
            Thread.sleep(1000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

我的Android代码也运行完美,它等待客户端 所以下面我发布由服务中的新线程运行的代码

 public void run() {

    try {

        server = new ServerSocket(port);// port = 5587 and ServerSocket intialised before itself

        while (true) {

            System.out.println("Waiting for client request");

            Socket socket = server.accept();
            //read from socket to ObjectInputStream object
            ObjectInputStream ois = new    ObjectInputStream(socket.getInputStream());
            //convert ObjectInputStream object to String
        String message = (String) ois.readObject();

            Log.d("sri","Message Received: " + message);
               } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

0 个答案:

没有答案