简体   繁体   English

在socket编程中,inputstream.read()不能在android中读取

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

I'm writing simple chat application with socket. 我正在用socket编写简单的聊天应用程序。 I'm connecting to my local server and if connecting without problem it shows in my textview "connected" and it shows that. 我正在连接到我的本地服务器,如果连接没有问题,它在我的textview中显示“已连接”,它显示了这一点。
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. 我的问题是,当我将两个设备连接到我的服务器并尝试使用其中一个发送按摩时,另一个不通过inputstream.read()获得按摩并且它阻止了代码。
Here is my code. 这是我的代码。 I appreciate anybodys help. 我很感激anybodys的帮助。

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))
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM