简体   繁体   中英

Java socket error while reading data from server at reader.readLine()

I am working on an android studio project in java which sends a picture to a python server for face detection, the server returns a "1" if there are any faces in the sent picture and a "0" if none.

The client socket is able to send the picture's base64 string to the server and the server receives it and detects faces as well but whenever my server socket returns a result in JSON form to the client socket, the thread at the client-side runs into exception block and the result isn't read and I get this error java.net.SocketException: Connection reset.

Help, please. Here's my code for both client and server-side.

Client side

private void sendMsg(final String obj) {
 final Handler handler = new Handler();
 Thread thread = new Thread(new Runnable() {
  @Override
  public void run() {
   try {
    Socket s = new Socket("192.168.10.4", 5000);
    OutputStream out = s.getOutputStream();
    PrintWriter output = new PrintWriter(out);
    output.println(obj);
    output.flush();
    BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
    final String ss = reader.readLine(); 
    handler.post(new Runnable() { 
     @Override
     public void run() {
      try {
       JSONObject obj = new JSONObject(ss);
       String lab = obj.getString("label");
       if (lab.equalsIgnoreCase("1")) {
        prediction.setText("face detected");
       } else {
        prediction.setText("face not detected");
       }
      } catch (JSONException e) {
       e.printStackTrace();
       Log.e("thread error: ", "error inside thread");
      }
     }
    });
   } catch (IOException e) {
    e.printStackTrace();
    Log.e("thread error: ", "error outside thread");
   }
  }
 });
 thread.start();
}

Server Side

import dlib
import base64
import io
import time
import codecs
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

import face_recognition
import cv2
from imageio import imread

import matplotlib.pyplot as plt
from io import StringIO
def threaded(c):
    data = c.recv(4096)

    #FACE DETECTION CODE WHICH ISNT THE PART OF THE PROBLEM#
    boxes = 1
    if(len(boxes)!= 0):
        label = "1"
    else:
        label = "0"

    c.send(  json.dumps({"label":label }).encode('utf-8')   )
    print( label )
    print( "Data" , json.dumps({"label": label })  )

    #print ("...")
    c.close()

port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((  "0.0.0.0" , port  )) 
print("socket binded to port", port )
s.listen(5) 
print("socket is listening")
all_conn = []
while True:
    conn, addr = s.accept()
    print('Connected to :', addr[0], ':', addr[1])
    all_conn.append( conn )
    start_new_thread(threaded, (conn,))
s.close()

Server should not close the socket. This is usually done by the client.

But it is good practice to close an open server socket after a certain timeout in which no data are received.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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