简体   繁体   中英

Android Server Pc Client

I'm trying to get a PC client to connect to an Android server. This is running in the emulator. I cannot get the PC client to connect.

The android server..

try {
        serverSocket = new ServerSocket( 1234 );

        //tell logcat the server is online
        Log.d("TCP", "C: Server Online...");

        while ( true ) {
            Log.d("TCP", "C: Waiting for client" );

            Socket client = serverSocket.accept();

            Log.d("TCP", "C: Client has connected" );

            BufferedReader in = new BufferedReader(
                    new InputStreamReader( 
                            client.getInputStream() ) );
            String input = in.readLine();

            Log.d("TCP", "C: " + input );

            client.close();
        }
    } catch ( Exception e ) {
        Log.d( "TCP", "C: " + e );
    }

and the PC client

String host = "127.0.0.1";

//Port the server is running on.
int port = 1234;

//Message to be sent to the PC
String message = "Hello from  pc.";
//Get the address of the host.
InetAddress remoteAddr = InetAddress.getByName( host );

//Tell the user that we are attempting a connect.
System.out.println("Attempting connect");

//Make the connection
Socket socket = new Socket(host, port);

//Tell user the connection was established
System.out.println("Connection made");

//Make the output stream to send the data.
OutputStream output = socket.getOutputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(
    new OutputStreamWriter(output)), true);

//Send the data.
out.println(message);

//Tell user the message was sent
System.out.println("Message sent");

I keep getting the message connection refused on the PC.. Can anyone help me with this? Cheers

From the docs for Emulator Networking ...

The virtual router for each instance manages the 10.0.2/24 network address space

Most importantly, the emulated device's own network address is 10.0.2.15.

I don't use the emulator but as far as I can tell you need to setup a redirection from 127.0.0.1:<host-port> to 10.0.2.15:<guest-port> . See the docs for Setting up Redirections through the Emulator Console .

As I said, I don't use the emulator but this is how I understand things work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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