使用dataoutputstream将字节写入套接字时,如何读取datainputstream?

时间:2018-08-02 14:58:45

标签: java android python sockets

我有一个使用python服务器接收/发送数据的android客户端。我能够使用dos.writeUTF()和dis.readUTF()正确向服务器发送和接收数据。但是writeUTF()给服务器端带来了问题,因为我不需要它写入的第一个到第二个字节,因此我在正确解析数据时遇到了问题。所以我选择使用dos.write(b,int,b.length)代替,它在服务器端工作得很好。但是我不确定现在如何处理输入流。

这是android客户端:

public class ExecuteCommand extends Activity implements View.OnClickListener {
EditText message;
TextView message_received;
Button send_button;
String serverResponse="";
String ip="192.168.1.110";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_execute_command);
    message = (EditText)findViewById(R.id.editText1);
    message_received=(TextView) findViewById(R.id.server_output);
    send_button = (Button)findViewById(R.id.button1);
    send_button.setOnClickListener(this);
}

public void onClick(View arg0) {

    Thread t = new Thread(){

        @Override
        public void run() {
            try {
                Socket s = new Socket(ip, 9999);
                OutputStreamWriter osw= new OutputStreamWriter(s.getOutputStream(), "UTF-8");
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                byte[] bufO=message.getText().toString().getBytes("UTF-8");
                dos.write(bufO,0,bufO.length);
                dos.flush();
                dos.close();

                DataInputStream dis = new DataInputStream(s.getInputStream());
                byte[] bufI= new byte[1024];
                int bytesread= dis.read(bufI);
                serverResponse= String.valueOf(bytesread);
                dis.close();
                s.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    if(message.getText().toString().equals("")){
        Toast.makeText(this, "Empty command", Toast.LENGTH_SHORT).show();
    }
    else{
        t.start();
        Toast.makeText(this, "Command sent", Toast.LENGTH_SHORT).show();
        message_received.append("Server Output: "+serverResponse + "\n");
    }
}
}

这是Python服务器:

import socketserver
import socket


class MyHandler(socketserver.BaseRequestHandler):
        def handle(self):
                self.sentence= self.request.recv(1024).strip()
                self.num=len(self.sentence)

                print(self.sentence.decode('utf-8'))
                self.request.sendall(self.sentence.encode('utf-8'))


def main():
        print ("Opening socket")
        host='192.168.1.110'
        port=9999
        server1=socketserver.TCPServer((host,port),MyHandler)
        print ("Running server")
        server1.serve_forever()

main()

1 个答案:

答案 0 :(得分:0)

您可以做这样的事情-

 BufferedReader reader=new BufferedReader(new InputStreamReader(s.getInputStream()));
String response=reader.readLine();