无法通过套接字从PC接收数据到Android

时间:2016-03-17 11:02:59

标签: android c++ sockets

我将我的PC设置为服务器,将我的Android手机设置为客户端。我已验证服务器是否在Windows中使用telnet命令发送数据。我的手机可以连接到服务器,但没有接收/显示数据。

我使用此代码在 PC -

中发送数据
char msg[32] = "message";
int sent = send(new_socket, msg, strlen(msg), 0);

我使用此代码接收 Android -

中的数据
public void onClickConnect(View view) {
    serverIP = textIP.getText().toString();
    new ConnectTask().execute("");
}

public class ConnectTask extends AsyncTask<String, String, TcpClient> {

    @Override
    protected TcpClient doInBackground(String... message) {
        mTcpClient = new TcpClient(serverIP, new TcpClient.OnMessageReceived() {
            @Override
            public void messageReceived(String message) {
                Log.i("Debug","Input message: " + message);
            }
        });
        mTcpClient.run();
        return null;
    }
}
--- TcpClient.java ---
public class TcpClient {

private String SERVER_IP;
public static final int SERVER_PORT = 8080;
private String mServerMessage;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter mBufferOut;
private BufferedReader mBufferIn;

public TcpClient(String IPAddress, OnMessageReceived listener) {
    mMessageListener = listener;
    SERVER_IP = IPAddress;
}

public void run() {
    mRun = true;
    try {
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
        Socket socket = new Socket(serverAddr, SERVER_PORT);
        try {
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (mRun) {
                mBufferIn.readLine(mServerMessage);
                if (mServerMessage != null && mMessageListener != null) {
                    mMessageListener.messageReceived(mServerMessage);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }

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

public interface OnMessageReceived {
    public void messageReceived(String message);
}
}

0 个答案:

没有答案