我有服务器和客户端。
我的问题是我的客户一次只能从BufferedReader in
收到一行。要接收下一行,客户必须回复。如何让客户端立即接收所有输入?例如,多行输入。
try (
Socket socket = new Socket(hostName, portNumber); //Connect to server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //The socket output stream sends an output to the server
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream())); //The socket input stream receives an output from the server
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in)); //The BufferedReader allows the client's input to be iterated through
String fromServer,
fromUser;
while ((fromServer = in.readLine()) != null) { //while there is an input from the server
System.out.println("Server: " + fromServer); //Print the input
fromUser = stdIn.readLine(); //Receive a line of user input
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser); //Send it out to the server
}
}
} catch [...]
答案 0 :(得分:0)
您可以使用不同的线程 - 一个用于发送消息,另一个用于接收消息。
客户端代码:
class Client5 extends Thread{
static Socket s;
static int end=0;
public void run(){
String str1;
//read data coing from server
try{
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
while(end==0)//recieve from server
{
str1=br.readLine();
System.out.println("from server:"+str1);
}
br.close();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args) throws Exception{
s=new Socket("192.168.43.231",1111);
//send data to server
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
//read from keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));
String str;
Client5 read=new Client5();
read.start();
//reapea till exit is typed by client
while(!(str=kb.readLine()).equals("exit")){
dos.writeBytes(str+"\n");//send to server
}
dos.writeBytes(str+"\n");
end=1;
s.close();
dos.close();
kb.close();
}
}