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

时间:2016-08-27 08:01:03

标签: android

我正在用socket编写简单的聊天应用程序。我正在连接到我的本地服务器,如果连接没有问题,它会显示在我的textview" connected"它表明了这一点 我的问题是,当我将两台设备连接到我的服务器并尝试使用其中一台设备发送按摩时,另一台设备通过inputstream.read()进行按摩并阻止代码。
这是我的代码。我感谢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();
    }
}

这是我的服务器代码:

1 个答案:

答案 0 :(得分:0)

喜欢这个

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