无法从服务器向客户端发送多条消息,反之亦然

时间:2014-12-07 22:40:19

标签: java networking

这是一个程序,其中客户端和服务器将相互交换用户输入的消息。 但是,我只能向服务器和客户端发送一条消息。之后我无法输入任何其他内容。

客户端输出:

count is 0 ->enter message ->hi ->hello->reached 1 times

服务器端输出:

(port number varies)59262->count is 0->hi->enter message->hello->reached 1 times

我认为它在第一次之后没有进入for循环,但我不知道为什么。任何帮助表示赞赏。

客户代码:

public class MessageClient {
public static void main(String[] arg) {
    BufferedReader in = null;
    int count = 0;
    try {
        Socket s = new Socket(arg[0],Integer.parseInt(arg[1]));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        Scanner scan = new Scanner(System.in);
        do {
        System.out.println("count is "+count);  
        System.out.println("enter message");
        String message = scan.nextLine();
        out.println(message);
        System.out.println(in.readLine());
        count++;
        System.out.println("reached "+count+" times");
        }
        while(in.readLine() != "quit");
    }catch(IOException e ) {
        System.out.println(e);
    }
}

}

服务器代码:

import java.util.*;
import java.net.*;
import java.io.*;

public class MessageServer {
public Socket d;
public ServerSocket serverSocket;

public MessageServer() throws IOException {
    serverSocket = new ServerSocket(0); 
}

public void run() {
    BufferedReader in;
    int count = 0;
    try {
        d = serverSocket.accept();
        in = new BufferedReader(new InputStreamReader(d.getInputStream()));
        Scanner scan = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(d.getOutputStream(),true);
        do{
        System.out.println("count is "+count);
        System.out.println(in.readLine());
        System.out.println("Enter message");
        String message = scan.nextLine();
        pw.println(message);
        count++;
        System.out.println("reached "+count+" times");
        }while(in.readLine()!= "quit");

    } catch(IOException e) {
        System.out.println(e);  
    }
}
public int getLocalPort() {
    return serverSocket.getLocalPort();
}
public static void main(String[] arg) throws IOException{
    MessageServer m = new MessageServer();
    System.out.println(m.getLocalPort());
    m.run();

}
}

0 个答案:

没有答案