无法使用套接字

时间:2017-02-20 14:05:45

标签: java android python sockets tcp

我已经尝试了一切来实现这个目标。基本上我有一个Android应用程序,它从本地网络连接上的基于Python的服务器接收数据。我可以收到数据没问题。但是,当我尝试发送数据时,App崩溃并且Python服务器收到空白数据。我尝试了几种不同的方法,但没有工作。这是我编写的用于接收消息的Python方法:

   def checkReply(self):
    reply = "no reply yet"
    self.conn.settimeout(1)
    try:
        test =  self.conn.recv(1024)
    except:
        self.conn.timeout;
        print("I failed to hear this") #Debug to help see if I have heard an incomming message
    try:
        data = test.decode()

        reply = data
    except:
        print("I failed to decode this") #Debug to help see if I could not decode an incomming message
    print(reply)
    self.conn.settimeout(0)

我的Android应用程序上的客户端如下所示:

public class Client extends AsyncTask<Void, Void, Void> {

String dstAddress;
int dstPort;
String response = "No data has been sent yet";
TextView textResponse;
Socket socket = null;


Client(String addr, int port, TextView textResponse) {
    dstAddress = addr;
    dstPort = port;
    this.textResponse = textResponse;
}

@Override
protected Void doInBackground(Void... arg0) {

    Socket socket = null;

    try {
        socket = new Socket(dstAddress, dstPort);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                1024);
        byte[] buffer = new byte[1024];

        int bytesRead;
        InputStream inputStream = socket.getInputStream();

     /*
      * notice: inputStream.read() will block if no data return
      */
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
            response = byteArrayOutputStream.toString("Ascii");
        }

        byteArrayOutputStream.flush();


    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response = "UnknownHostException: " + e.toString();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response = "IOException: " + e.toString();
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;
}

@Override
protected void onPostExecute(Void result) {
    textResponse.setText(response);
    super.onPostExecute(result);
}

protected String getSite(){
    return response;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void returnMsg(){

        try (DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream())) {
            byte[] buf = "hello".getBytes("UTF-8");
            outToClient.writeBytes("Test");
            outToClient.flush();

        } catch (IOException e) {}




}

}

我不得不在物理设备上进行测试,因此我没有日志来跟踪错误消息。任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。在尝试通过套接字发回任何数据之前,我需要刷新缓冲区