简体   繁体   中英

Android 2-Way TCP/IP ServerSocket/Socket Communication

Using this great tutorial by the Java Code Geeks, I am easily able to create a client activity that sends data via TCP to a server's port 4000 using the following code:

public class Client extends Activity {

private Socket socket;

private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);      

    new Thread(new ClientThread()).start();
}

public void onClick(View view) {
    try {
        EditText et = (EditText) findViewById(R.id.EditText01);
        String str = et.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true);
        out.println(str);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

class ClientThread implements Runnable {

    @Override
    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            socket = new Socket(serverAddr, SERVERPORT);

        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

}
}

Then using their other snippet for the server activity I can catch messages using TCP on that port:

public class Server extends Activity {

private ServerSocket serverSocket;

Handler updateConversationHandler;

Thread serverThread = null;

private TextView text;

public static final int SERVERPORT = 6000;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    text = (TextView) findViewById(R.id.text2);

    updateConversationHandler = new Handler();

    this.serverThread = new Thread(new ServerThread());
    this.serverThread.start();

}

@Override
protected void onStop() {
    super.onStop();
    try {
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

class ServerThread implements Runnable {

    public void run() {
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {

            try {

                socket = serverSocket.accept();

                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();

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

class CommunicationThread implements Runnable {

    private Socket clientSocket;

    private BufferedReader input;

    public CommunicationThread(Socket clientSocket) {

        this.clientSocket = clientSocket;

        try {

            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

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

    public void run() {

        while (!Thread.currentThread().isInterrupted()) {

            try {

                String read = input.readLine();

                updateConversationHandler.post(new updateUIThread(read));

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

}

class updateUIThread implements Runnable {
    private String msg;

    public updateUIThread(String str) {
        this.msg = str;
    }

    @Override
    public void run() {
        text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
    }
}
}

My question is how can I make it so these 2 can communicate back and forth?

Android -> Server(4000) -> Android(4001)?

In other words how can I make my app help the device act as both the client (sending out data to another device on port 4000) and the server (listening for data on port 4001) at the same time?

On the Server side change the port to 5000 (same as Client) instead of 6000:

And you need to update the following class because you don't want to create a new socket, you should use the one already created (in the Client part). NB: the socket given as an argument to CommunicationThread is the socket that you supposedly already created (Client part).

class ServerThread implements Runnable {

public void run() {
    while (!Thread.currentThread().isInterrupted()) {
            CommunicationThread commThread = new CommunicationThread(socket);
            new Thread(commThread).start();

        }
    }
}

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