簡體   English   中英

Java套接字:連接但沒有流?

[英]Java Sockets: Connection but no Stream?

我正在嘗試編寫一些SocketServer和合適的ClientApplet。 連接有效(我回顯了傳入/關閉的連接),但是服務器未獲得任何InputStream。 我只是無法解決問題並感到有點失落:/

完整的項目在這里

這是我服務器的負責部分:

MessageService.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) {}
        }
    }
}
}

部分客戶

QueueOut.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);
}
}

我已將帖子減少到(我認為)必要的部分:)

即使未使用輸入流,也請嘗試先獲取輸入流,即使您沒有使用它,也應將客戶端和服務器上的逆序匹配(如其他類似線程中所述)。

編輯:

另請參閱套接字編程

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM