开发者

Android Socket Programming Emulator Communication

I need to send messages between to emulator on same pc by the use of Socket Programming first Emulator behave Like a Server and Second one behave Like Client. But I am unable to envoke my Server Emulator and passing messages. I am new in android can any body plz help me out.

My Code

Server side Code

package com.test.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

public class ServerActivity extends Activity {
    private TextView serverStatus;

    // DEFAULT IP
    public static String SERVERIP = "192.168.0.20"; // 10.0.2.15
    // DESIGNATE A PORT
    public static final int SERVERPORT = 4000;  // 8080
    private Handler handler = new Handler();
    private ServerSocket serverSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server);
        serverStatus = (TextView) findViewById(R.id.server_status);
        SERVERIP = getLocalIpAddress();
        Thread fst = new Thread(new ServerThread());
        fst.start();

    }

    public class ServerThread implements Runnable {
        public void run() {
            try {
                if (SERVERIP != null) {
                    handler.post(new Runnable() {

                        @Override
                        public void run() {
                            serverStatus.setText("Listening on IP: " + SERVERIP);
                        }
                    });

                    serverSocket = new ServerSocket(SERVERPORT);

                    while (true) {
                        // LISTEN FOR INCOMING CLIENTS
                        Socket client = serverSocket.accept();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Connected.");
                            }

                        });

                        try {
                            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                            String line = null;
                            while ((line = in.readLine()) != null) {
                                Log.d("ServerActivity", line);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        // DO WHATEVER YOU WANT TO THE FRONT END
                                        // THIS IS WHERE YOU CAN BE CREATIVE
                                    }
                                });

                            }

                            break;
                        } catch (Exception e) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                                }
                            });

                            e.printStackTrace();
                        }
                    }
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Couldn't detect internet connection.");
                        }
                    });
                }

            } catch (Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Error");
                    }
                });

                e.printStackTrace();
            }
        }

    }

    // GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
                }
            }
        } catch (SocketException ex) {
            Log.e("ServerActivity", ex.toString());
        }

        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
            serverSocket.close();

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

Client Side Code :

package com.test.android;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ClientActivity extends Activity {
    private EditText serverIp;
    private Button connectPhones;
    private String serverIpAddress = "192.168.0.20"; // 10.0.2.15 // machin ip 192.168.0.20 // default ip:- 10.0.2.2 
    private boolean connected = false;
    private Handler handler = new Handler();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client);
        serverIp = (EditText) findViewById(R.id.server_ip);
        connectPhones = (Button) findViewById(R.id.connect_phones);
        connectPhones.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!connected) {
                     serverIpAddress = serverIp.getText().toString();
                     if (!serverIpAddress.equals("")){
                         Thread cThread = new Thread(new ClientThread());
                          cThread.start();   
                     }   

                }

            }
        });
    }
}

File ClientThread.java:

package com.test.android;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.util.Log;
import android.widget.EditText;

public class ClientThread implements Runnable {
    private String serverIpAddress = "192.168.0.20"; //10.0.2.15
    private boolean connected = false;
    @Override
    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
            connected = true;

            while (connected){
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                    out.println("Hey Server!");
                    Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    // TODO: handle exception
                }
                socket.close();
                Log.d("ClientActivity", "C: Closed.");  
            }
        } catch (Exception e) {
            Log.e("ClientActivity", "C: 开发者_运维百科Error", e);
            connected = false;
        }
    }
}


The following works on my dev environment of Android Studio 4.1.1 on macOS Big Sur 11.1. It's a simple chess game over socket.

To setup port redirection on emulator, go to terminal.

to find out port number used by emulator console, run

~/Library/Android/sdk/platform-tools/adb devices

to find out authentication token, run

cat ~/.emulator_console_auth_token

to telnet emulator console, run (assuming port number is 5554)

telnet localhost 5554

to get authenticated, run

auth your_auth_token

to list active redirections, run

redir list

to add redirection, run (assuming 50000 is host port and 50001 is guest port)

redir add tcp:50000:50001

to go back to telnet prompt, press

ctrl + ]

to quit telnet, run

close

Android chess in Kotlin: https://github.com/zhijunsheng/chess-kotlin-andr

iOS chess of UIKit (used as testing socket client): https://github.com/zhijunsheng/chess-uikit-ios


i have not tried your code, but i think you should use 70 as the SERVERPORT.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜