简体   繁体   中英

in socket programming inputstream.read() dosen't read in android

I'm writing simple chat application with socket. I'm connecting to my local server and if connecting without problem it shows in my textview "connected" and it shows that.
My problem is when i connected two devices to my server and trying to send massage with one of them, the other one dosen't get the massage via inputstream.read() and it block the code.
Here is my code. I appreciate anybodys help.

public class CommsThread extends Thread {<br>
    static Context context;<br>

    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public CommsThread(Socket sock) {
        socket = sock;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.d("SocketChat", e.getLocalizedMessage());
        }
        inputStream = tmpIn;
        outputStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        while (true) {
            try {
                bytes = inputStream.read(buffer);
                MainActivity.UIupdater.obtainMessage(0, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(byte[] bytes) {
        try {
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException e) {
        }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) { }
    }
}

public class MainActivity extends Activity {<br>
    static final String NICKNAME = "Wei-Meng";<br>
    InetAddress serverAddress;<br>
    Socket socket;<br>
    static TextView txtMessagesReceived;<br>
    EditText txtMessage;<br>
    CommsThread commsThread;<br>

    static Handler UIupdater = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int numOfBytesReceived = msg.arg1;
            byte[] buffer = (byte[]) msg.obj;
            String strReceived = new String(buffer);
            strReceived = strReceived.substring(0, numOfBytesReceived);
            txtMessagesReceived.setText(txtMessagesReceived.getText().toString() + strReceived);
        }
    };

    private class CreateCommThreadTask extends AsyncTask<Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                serverAddress = InetAddress.getByName("172.20.10.3");
                socket = new Socket(serverAddress, 80);
                commsThread = new CommsThread(socket);
                commsThread.start();
                if (socket.isConnected())
                    txtMessagesReceived.setText("connected");
                sendToServer(NICKNAME);
            } catch (UnknownHostException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }
    private class WriteToServerTask extends AsyncTask<byte[], Void, Void> {
        protected Void doInBackground(byte[]...data) {
            commsThread.write(data[0]);
            return null;
        }
    }
    private class CloseSocketTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                socket.close();
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }

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

        CommsThread.context = this;

        txtMessage = (EditText) findViewById(R.id.txtMessage);
        txtMessagesReceived = (TextView) findViewById(R.id.txtMessagesReceived);
    }

    public void onClickSend(View view) {
        sendToServer(txtMessage.getText().toString());
    }
    private void sendToServer(String message) {
        byte[] theByteArray = message.getBytes();
        new WriteToServerTask().execute(theByteArray);
    }
    @Override
    public void onResume() {
        super.onResume();
        new CreateCommThreadTask().execute();
    }
    @Override
    public void onPause() {
        super.onPause();
        new CloseSocketTask().execute();
    }
}

here's my server code:

Do Like this

String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);

try (
    Socket echoSocket = new Socket(hostName, portNumber);
    PrintWriter out =
        new PrintWriter(echoSocket.getOutputStream(), true);
    BufferedReader in =
        new BufferedReader(
            new InputStreamReader(echoSocket.getInputStream()));
    BufferedReader stdIn =
        new BufferedReader(
            new InputStreamReader(System.in))
)

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