多线程套接字服务器在其生命周期内仅处理一个请求 [英] Multithreaded socket server is only working with one request during its lifetime

查看:57
本文介绍了多线程套接字服务器在其生命周期内仅处理一个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还有一个关于我的推送服务器的问题.出于某种原因,服务器在其生命周期内只会接受一个连接.即使在第一个连接关闭后,服务器也不会做任何事情.我怀疑线程没有被生成,因为它没有拒绝连接.

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.

这里是服务器的代码: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!

推荐答案

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

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

这行代码是A级废话.如果 inputLine 为空,则对等方已关闭套接字,您必须退出循环并自行关闭套接字.目前你忽略了EOS条件并永远循环.

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.

这篇关于多线程套接字服务器在其生命周期内仅处理一个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆