简体   繁体   English

套接字编程未在真实的android设备中连接

[英]Socket programming does not connect in real android device

I want to send data(simple text) from android to computer and show received text in computer application, for that reason i created 2 applications which first one run in android device(client) and second one run in computer(server). 我想将数据(纯文本)从android发送到计算机,并在计算机应用程序中显示接收到的文本,因此我创建了2个应用程序,其中第一个在android设备(客户端)中运行,第二个在计算机(服务器)中运行。 i have created both applications with java language. 我已经用Java语言创建了两个应用程序。

when i run android application in genymotion, everything is ok and both applications could connect together but when i run android application in real device applications cannot connect together while both are in same network and ip address is correct. 当我在genymotion中运行android应用程序时,一切正常,并且两个应用程序都可以连接在一起,但是当我在真实设备中运行android应用程序时,虽然它们都在同一网络中,并且IP地址正确,但应用程序无法连接在一起。
codes for computer application(server): 计算机应用程序(服务器)的代码:

try {
     ServerSocket serverSocket = new ServerSocket(9000);
     Socket socket = serverSocket.accept();

     DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

     while(true){
         String message = bufferedReader.readLine();
         message(message);
     }
} catch (IOException e) {
     e.printStackTrace();
}

codes for android application(Client): android应用程序的代码(客户端):

new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                message("Waiting for Connection...");
                socket= new Socket("192.168.1.6", 9000);
                message("Connected...");

                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(socket==null){ return; }

            try {
                String message = edtMessage.getText().toString() + "\n";
                dataOutputStream.write(message.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
         message(message);
     }
} catch (IOException e) {
     e.printStackTrace();
}

screen shot(application connected when i run android application in genymotion 屏幕截图(当我在genymotion中运行android应用程序时,应用程序已连接

please guide me for resolve that issue. 请指导我解决该问题。 Thanks 谢谢

You cannot write to the output stream in the handler of an on click listener. 您不能在on click侦听器的处理程序中写入输出流。 You should do that in a thread too. 您也应该在线程中执行此操作。

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

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