我正在尝试创建一个多线程聊天室,多个人可以附加到该聊天室。目的是当一个人发送一条消息时,该消息被打印在其他人的屏幕上。这是服务器代码:
package edu.fcps.ab;
import java.io.*;
import java.net.*;
import java.util.*;
public class TestServer implements Runnable{
private int port;
public static ServerSocket serverSock;
public static Vector<PrintWriter> outputs = new Vector<PrintWriter>();
public PrintWriter output;
public BufferedReader input;
public TestServer(int p) {
port = p;
}
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter port number");
int port = scan.nextInt();
TestServer ts = new TestServer(port);
Thread t = new Thread(ts);
t.start();
}
@Override
public void run() {
try {
if(serverSock == null)
serverSock = new ServerSocket(port);
Socket sock = serverSock.accept();
TestServer ts = new TestServer(port);
Thread t = new Thread(ts);
t.start();
output = new PrintWriter(sock.getOutputStream(), false);
outputs.add(output);
input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
while(t.isAlive()) {
String message = input.readLine();
if(message != null) {
System.out.println(message);
for(PrintWriter w : outputs) {
w.println(message);
w.flush();
}
}
}
} catch(Exception e) {
System.out.println("An error occurred");
e.printStackTrace();
}
}
public PrintWriter getOutput() {
return output;
}
}
这是客户端代码:
package edu.fcps.ab;
import java.io.*;
import java.net.*;
import java.util.*;
public class TestClient implements Runnable{
private String username;
public PrintWriter out;
public static void main (String args[]) {
TestClient tc = new TestClient();
Thread t = new Thread(tc);
t.start();
}
@Override
public void run() {
Scanner s = new Scanner(System.in);
System.out.println("Enter port");
int port = s.nextInt();
String ip = "127.0.0.1";
try {
Socket sock = new Socket(ip, port);
System.out.println("Successfully connected");
System.out.println("Enter username");
username = s.next();
System.out.println("Welcome " + username);
out = new PrintWriter(sock.getOutputStream(), true);
out.println(username + " connected");
InputStream stream = sock.getInputStream();
Scanner input = new Scanner(stream);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String sent;
while(true) {
if(stream.available() > 0) {
if(input.hasNextLine()) {
String message = input.nextLine();
String[] split = message.split(" ");
if(!(split[0].contains(username)))
System.out.println(message);
}
}
sent = stdin.readLine();
if(sent != null) {
out.println(username + ": " + sent);
}
}
} catch(Exception e) {
out.println(username + " disconnected");
}
}
}
当前,可以将多个人附加到该邮件上,并且该邮件将在服务器端打印出所有消息,但是并不能在所有客户端上打印这些消息。为什么会这样?
答案 0 :(得分:1)
...但是消息并没有在所有客户端上打印。为什么会这样?
之所以发生这种情况,是因为所有客户端都调用stdin.readLine()
并阻塞在那里,直到有输入行可用为止。此后,他们继续进行while(true)
循环并打印最多一条消息,然后再次阻塞stdin.readLine()
。