Java 套接字:连接但没有流



我正在尝试编写一个小的SocketServer和一个合适的ClientApplet。连接工作(我回显传入/关闭连接(,但服务器没有获得任何输入流。我只是无法解决问题,感觉有点迷茫:/

完整的项目在这里。

这是我服务器的责任部分:

消息服务.java

public class MessageService implements Runnable {
private final Socket client;
private final ServerSocket serverSocket;
MessageService(ServerSocket serverSocket, Socket client) {
    this.client = client;
    this.serverSocket = serverSocket;
}
@Override
public void run() {
    PrintWriter out = null;
    BufferedReader in = null;
    String clientName = client.getInetAddress().toString();
    try {
        out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
        in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String line;
        System.out.println("Waiting for "+clientName);
                    /* HERE I TRY TO GET THE STREAM */
        while((line = in.readLine()) != null) {
            System.out.println(clientName + ": " + line);
            out.println(line);
            out.flush();
        }
    }
    catch (IOException e) {
        System.out.println("Server/MessageService: IOException");
    }
    finally {
        if(!client.isClosed()) {
            System.out.println("Server: Client disconnected");
            try {
                client.close();
            }
            catch (IOException e) {}
        }
    }
}
}

客户的一部分

排队.java

public class QueueOut extends Thread {
Socket socket;
public ConcurrentLinkedQueue<String> queue;
PrintWriter out;
public QueueOut(Socket socket) {
    super();
    this.socket = socket;
    this.queue = new ConcurrentLinkedQueue<String>();
    System.out.print("OutputQueue started");
}
@Override
public void start() {
    try {
        out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        System.out.println("Running outputqueue");
        while(true) {
            if(this.queue.size() > 0) {
                String message = this.queue.poll();
                System.out.println("Sending "+message);
                out.println(message+"n");
            }
        }
    }
    catch (IOException ex) {
        System.out.println("Outputqueue: IOException");
    }
}
public synchronized void add(String msg) {
    this.queue.add(msg);
}
}

我已经将我的帖子减少到(我认为(必要的部分:)

在获取输出流之前尝试获取输入流,即使您没有使用它,也应该匹配客户端和服务器上的反向顺序(如另一个类似线程中所述(。

编辑:

另请参阅套接字编程

祝你好运!

相关内容

  • 没有找到相关文章

最新更新