java.net.SocketException: Connection reset by peer: socket write error

主要实现功能:前端点击上传文件,后台通过socket通信,打包http文件头+文件一并发送到客户端(硬件)

设计思路:
启动javaweb(Tomcat服务器)的同时建立了一个socket连接;
通过点击网页上传文件的按钮,将文件保存到本地,同时调用socketThread线程的发送文件的方法sendfile()

控制器:

        //socket
        upFileService upFileService=new upFileService();
        upFileService.upFile(finalPath);
 

Service:

 

public class upFileService {
    public String upFile(String finalPath) {
        System.out.println(finalPath);
        try {
            Thread3.send(finalPath);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return finalPath;
    }
}
 
private static void sendFile(String finalURL, Socket socket)throws Exception{
        try {
 
            System.out.println("server is listening port:" + socket.getLocalPort());
            while (true) {
 
                System.out.println("build a link with client:" + socket.getInetAddress()
                        + ":" + socket.getPort());
                InputStream socketInputStream = socket.getInputStream();
                //等待HTTP请求
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                byte[] buffer = new byte[socketInputStream.available()];
                socketInputStream.read(buffer);
                String request = new String(buffer);
                System.out.println(request);
                String firstLineOfRequest = request.substring(0, request.indexOf("\r\n"));
                String[] firstLineParts = firstLineOfRequest.split(" ");
                String uri = firstLineParts[1];
 
                //
                String contentType;
                if (uri.contains(".html") || uri.contains(".htm")) {
                    contentType = "text/html";
                } else {
                    if (uri.contains(".jpg") || uri.contains(".jpeg")) {
                        contentType = "image/jpeg";
                    } else {
                        contentType = "application/octet-stream";
                    }
                }
                //
                Thread3 thread3=new Thread3();
                File file=new File(finalURL);
                long fileSizes = thread3.getFileSizes(file);
                System.out.println("文件大小:"+thread3.FormetFileSize(fileSizes));
 
                //response result
                String responseFirstLine = "HTTP/1.1 200 OK\r\n";
                String responseSize="Content-Length:"+fileSizes+ "\r\n";
                String responseHeader = "Content-Type:" + contentType + "\r\n\r\n";
                InputStream inputStream = new FileInputStream(finalURL);
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(responseFirstLine.getBytes());
                outputStream.write(responseSize.getBytes());
                outputStream.write(responseHeader.getBytes());
//                //
//                Server s=new Server();
//                File file=new File("D:\\IDEAProjectTmpFile\\rtthread.rbl");
//                long fileSizes = s.getFileSizes(file);
//                System.out.println("文件大小:"+s.FormetFileSize(fileSizes));
 
                //
                int len = 0;
                byte[] bytes = new byte[1024];
 
                do{
                    len = inputStream.read(bytes);
                    outputStream.write(bytes, 0, len);
                }while (inputStream.available()!=0);
 
                //2022-3-14 21:00修改部分
//                while ((len = inputStream.read(bytes)) != -1) {
//                    outputStream.write(bytes, 0, len);
//                    outputStream.flush();
//                }
 
                //等待客户接受HTTP响应结果
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void send(String finalPath) throws Exception {
        // 只有一个客户端连接的情况下使用这个方法
        Socket socketOne = SocketSer.getConnectedSockets();
        if (socketOne == null) {
            System.out.println("没有已连接的客户端");
            return;
        }
//        Thread3 thread3=new Thread3();
//        Socket socket = thread3.socket;
//        if (socket == null) {
//            System.out.println("没有已连接的客户端");
//            return;
//        }
        sendFile(finalPath,socketOne);
    }

最后控制台打印报错:java.net.SocketException: Connection reset by peer: socket write error

2021329998
server is listening port:12288
build a link with client:/192.168.1.122:49155
GET / HTTP/1.1
Host: 192.168.1.125
User-Agent: RT-Thread HTTP Agent
 
 
文件大小:243.58K
java.net.SocketException: Connection reset by peer: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
    at com.atguigu.mvc.socketServer.Thread3.sendFile(Thread3.java:133)
    at com.atguigu.mvc.socketServer.Thread3.send(Thread3.java:172)
    at com.atguigu.mvc.service.upFileService.upFile(upFileService.java:15)
    at com.atguigu.mvc.controller.FileUpAndDownController.testUp(FileUpAndDownController.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:807)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:750)
 

还没找到解决办法
请问一下怎么解决这个问题┭┮﹏┭┮

你可能感兴趣的:(java,服务器,tomcat,后端)