Multithreaded socket server is only working with one request during its lifetime [closed]

旧街凉风 提交于 2019-12-13 10:31:31

问题


I have yet another question about my push server. For some reason the server will only accept one connection during it's lifetime. Even after the first connection has been closed, the server won't do anything. I have a suspicion that the thread isn't being spawned because it's not refusing the connection.

Here is the code to the server: http://docs.oracle.com/javase/tutorial/networking/sockets/examples/KKMultiServer.java

I used the example because it's just what I needed. I left this code unchanged. It's the thread I really worked with...

import java.net.*;
import java.io.*;

public class KKMultiServerThread extends Thread {
    private Socket socket = null;

    public KKMultiServerThread(Socket socket) {
            super("KKMultiServerThread");
            this.socket = socket;
    }

    public void run() {
            try {
                    final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String inputLine, outputLine;
                    out.println("connected");
                    boolean loggedin = false;
                    String username="";
                    String password="";
                    String deviceid="";
                    while (true) {
                    //deal with login handshake
                            if ((inputLine = in.readLine()) == null) inputLine="";
                            if (!loggedin) {
                                   Logs the user in...
                                   Also does things with files and keeps reading and writing to the client...
                    }
                    out.close();
                    in.close();
                    socket.close();
            } catch (IOException e) {
                    e.printStackTrace();
            }
    return;
    }
}

What could be going wrong? I close the socket and all of the streams like I should but even then it should still work, shouldn't it?

Thank you for the continued support!


回答1:


if ((inputLine = in.readLine()) == null) inputLine="";

This line of code is grade A nonsense. If inputLine is null, the peer has closed the socket, and you must exit the loop and close the socket yourself. At present you are ignoring the EOS condition and looping forever.



来源:https://stackoverflow.com/questions/14077960/multithreaded-socket-server-is-only-working-with-one-request-during-its-lifetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!