2

私は小さな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);
}
}

私は自分の投稿を(私が思うように)必要な部分に減らしました:)

4

1 に答える 1

0

出力ストリームを取得する前に入力ストリームを取得してみてください。使用していない場合でも、クライアントとサーバーで逆の順序を一致させる必要があります(別の同様のスレッドで説明されています)。

編集:

ソケットプログラミングも参照してください

幸運を!

于 2012-05-20T15:25:35.877 に答える