Multithreaded socket server is only working with o

2019-09-20 17:19发布

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条回答
疯言疯语
2楼-- · 2019-09-20 18:15

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.

查看更多
登录 后发表回答