How to connect to PC (server) using sockets with Android app (client)?

假装没事ソ 提交于 2021-02-11 14:27:56

问题


I have a server set up on my PC (using Hercules), which is listening on a port # and waiting for a connection. I can't get the android app to receive messages from the server however on my android emulator (Strangely I can send messages to the server), and I can't do either from my physical android phone.

All the examples I'm finding online involve android devices connecting to each other, like this one: https://www.coderzheaven.com/2017/05/01/client-server-programming-in-android-send-message-to-the-client-and-back/

Would I still be able to connect to a PC by just implementing the client side on my android app? What changes would I have to make otherwise?

Directly copy pasting hasn't worked for me...

(Btw the phone and PC are both connected to the same ethernet network, not wifi if that makes a difference)

Thanks!

edit: Turns out my PC was on a different subnet from my phyiscal android phone, and so changing the PC to be on the same subnet as the phone fixed the problem of my phone not being able to even connect, but now it can connect it seems and send messages to the PC, but again not able to receive messages from the hercules server

edit2: My client code (android app)

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


public static final int SERVERPORT = xxxx;
public static final String SERVER_IP = "xxx.xxx.x.xxx"; 

private ClientThread clientThread;
private Thread thread;
private LinearLayout msgList;
private Handler handler;
private int clientTextColor;
private EditText edMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setTitle("Client");
    clientTextColor = ContextCompat.getColor(this, R.color.colorAccent);
    handler = new Handler();
    msgList = findViewById(R.id.msgList);
    edMessage = findViewById(R.id.edMessage);
}

public TextView textView(String message, int color) {
    if (null == message || message.trim().isEmpty()) {
        message = "<Empty Message>";
    }
    TextView tv = new TextView(this);
    tv.setTextColor(color);
    tv.setText(message + " [" + getTime() + "]");
    tv.setTextSize(20);
    tv.setPadding(0, 5, 0, 0);
    return tv;
}

public void showMessage(final String message, final int color) {
    handler.post(new Runnable() {
        @Override
        public void run() {
            msgList.addView(textView(message, color));
        }
    });
}

@Override
public void onClick(View view) {

    if (view.getId() == R.id.connect_server) {
        msgList.removeAllViews();
        showMessage("Connecting to Server...", clientTextColor);
        clientThread = new ClientThread();
        thread = new Thread(clientThread);
        thread.start();
        showMessage("Connected to Server...", clientTextColor);
        return;
    }

    if (view.getId() == R.id.send_data) {
        String clientMessage = edMessage.getText().toString().trim();
        showMessage(clientMessage, Color.BLUE);
        if (null != clientThread) {
            clientThread.sendMessage(clientMessage);
        }
    }
}

class ClientThread implements Runnable {

    private Socket socket;
    private BufferedReader input;

    @Override
    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);
            this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {

                String message = input.readLine();
                
                if (null == message || "Disconnect".contentEquals(message)) {
                    Thread.interrupted();
                    message = "Server Disconnected.";
                    showMessage(message, Color.RED);
                    break;
                }
                showMessage("Server: " + message, clientTextColor);
            }

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

    }

    void sendMessage(final String message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (null != socket) {
                        PrintWriter out = new PrintWriter(new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream())),
                                true);
                        out.println(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

String getTime() {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    return sdf.format(new Date());
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (null != clientThread) {
        clientThread.sendMessage("Disconnect");
        clientThread = null;
    }
}

}

来源:https://stackoverflow.com/questions/63904116/how-to-connect-to-pc-server-using-sockets-with-android-app-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!