简体   繁体   English

Java 在 reader.readLine() 从服务器读取数据时出现套接字错误

[英]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.我正在 java 中的 android 工作室项目上工作,该项目将图片发送到 python 服务器进行人脸检测,如果发送的图片中有任何人脸,则服务器返回“1”,如果没有,则返回“1”。

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.客户端套接字能够将图片的 base64 字符串发送到服务器,服务器接收它并检测人脸,但是每当我的服务器套接字以 JSON 形式向客户端套接字返回结果时,客户端的线程就会运行异常块并且未读取结果,我收到此错误 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.但是,在没有接收到数据的特定超时后关闭打开的服务器套接字是一种很好的做法。

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

相关问题 java-服务器未从客户端接收消息(reader.readLine()== null?) - java - server not recieving messages from client (reader.readLine() == null ?) Java reader.readLine()不会在文件中返回确切的行 - Java reader.readLine() dosn't return the exact line in the file 使用“ while(line = reader.readLine()!= null)”时,类型不匹配 - Type mismatch when using “while(line = reader.readLine() != null)” 如何从reader.readLine()返回的String中删除unicode空格 - how to remove unicode spaces from String returned by reader.readLine() Java Socket Server在读取数据时挂起 - Java Socket Server hangs while reading data 如何在使用reader.readLine()和sc.nextLine()时避免阻塞 - How to avoid blocking while using reader.readLine() and sc.nextLine() 使用ProcessBuilder执行Linux命令并从reader.readLine()获取NULL,尽管行数为102 - Using ProcessBuilder to execute Linux Command and getting NULL from reader.readLine() although line count is 102 line = reader.readline()结果与文字“F”的行为不同 - line = reader.readline() result does not behave same as a literal “F” 如何在reader.readLine()期间检测第一行和最后一行? - How to detect first and last line during reader.readLine()? bufferedReader reader.readline 直接回null - bufferedReader reader.readline directly goes back to null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM