简体   繁体   English

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

[英]How to read a datainputstream when using a dataoutputstream to write bytes to socket?

I have an android client that is receiving/sending data with a python server. 我有一个使用python服务器接收/发送数据的android客户端。 I was able to correctly send and receive data to the server using dos.writeUTF() and dis.readUTF(). 我能够使用dos.writeUTF()和dis.readUTF()正确向服务器发送和接收数据。 However writeUTF() was giving me problems server side because I didn't need the first to 2 bytes that it writes and so I have problems parsing the data correctly. 但是writeUTF()给服务器端带来了问题,因为我不需要它写入的第一个到第二个字节,因此我在正确解析数据时遇到了问题。 So I opted to use dos.write(b, int, b.length) instead and it worked great server side. 所以我选择使用dos.write(b,int,b.length)代替,它在服务器端工作得很好。 But I am not sure how to handle the input stream now. 但是我不确定现在如何处理输入流。

Here is the android client: 这是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");
    }
}
}

Here is the Python server: 这是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()

you may do something like this- 你可以做这样的事情-

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

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

相关问题 DataInputStream和DataOutputStream:读写多次 - DataInputStream and DataOutputStream: read and write several times 如何使用datainputstream从套接字读取 - How to read from socket using datainputstream 如何使用DataOutputStream和DataInputStream进行序列化/反序列化? - How to serialize/deserialize with DataOutputStream and DataInputStream? 如何在DataOutputStream中读取和写入整数-1 - How to read and write integer -1 into DataOutputStream 使用DataOutputStream将带有数组的字符串作为字节写入文件 - Write String with array as bytes to a file using DataOutputStream 使用DataInputStream从TCP套接字读取的字节之前的不需要的nul字符 - Unwanted nul characters preceding bytes from TCP socket read using DataInputStream 使用DataInputStream和DataOutputStream和套接字的管道断开 - Broken pipe using DataInputStream and DataOutputStream and sockets 使用DataInputStream读取小字节长度时读取性能降低 - Slow read performance using DataInputStream when it comes to reading small length of bytes 如何使用DataInputStream的方法读取DataOutputStream.writeBytes(String)写入的数据? - How to use the method of DataInputStream to read data writed by DataOutputStream.writeBytes(String)? 从DataOutputStream.writeUTF()读取时如何获取Java字符串的“原始”字节? - How to get 'original' bytes of a Java String when read from DataOutputStream.writeUTF()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM