简体   繁体   中英

Sockets with Android Client an PC Server

I've seen a few of these questions around, but none of the answers seem to resolve my problem. I want to display a message on my server (PC) from my client (Android phone, I actually have a physical device ). I have an extremely simple PC server:

public void run(int port) throws Exception
{
    ServerSocket ss = new ServerSocket(port);
    Socket sock = ss.accept();

    BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));

    System.out.println(reader.readLine());
}

(In my main void):

Server s = new Server();
s.run(4444);

And an extremely simple Android client:

package com.j03.client;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.net.*;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        try
        {
            runClient("10.0.2.2", 4444, "hey");
        }
        catch (Exception e)
        {
            TextView t = new TextView(this);
            t.setText(e.getMessage());
            setContentView(t);
        }
    }

    public static void runClient(String ip, int port, String message) throws Exception
    {
        Socket sock = new Socket(ip, port);
        PrintStream ps = new PrintStream(sock.getOutputStream());
        ps.println(message);
    }
}

I also have the proper internet permissions in my manifest file:

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

And the client code works fine as a PC Client. (PC Client to PC Server works fine).

but I can not get it to work on Android!

The PC server simply displays nothing. :(

Does anyone know what I could be doing wrong?

You also might be doing this all on the UI thread. I think android sometimes will kill your app if you do this and display Application is not responding dialogs.

The other poster is also correct about your Activity being empty until an exception occurs. I would fix that and try starting a separate thread with your runClient in it

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