【发布时间】:2013-12-27 21:16:45
【问题描述】:
我正在制作一个聊天室项目,其中服务器接受许多客户端,客户端写入的任何内容都会到达其他客户端,依此类推。 不幸的是,服务器最多接受 2 个客户端,并且在一个客户端写入输入后,它会出错。
public class Server2 {
private static ArrayList<Socket> clients;
private ServerSocket server;
DataOutputStream os;
DataInputStream in;
Socket s;
public Server2() throws IOException {
server = new ServerSocket(5000);
clients = new ArrayList<Socket>();
System.out.println("Waiting for connections...");
runOutput();
}
public void addClient() throws IOException {
s = server.accept();
clients.add(s);
System.out.println("A new Client has joined");
}
public void runOutput() {
Thread n = new Thread(new Runnable() {
public void run() {
try {
addClient();
} catch (IOException e) {
e.printStackTrace();
}
}
});
n.start();
Thread input = new Thread(new Runnable() {
public void run() {
try {
addClient();
in = new DataInputStream(s.getInputStream());
os = new DataOutputStream(s.getOutputStream());
String st = in.readLine();
System.out.println(st);
os.writeBytes(st);
for(int i = 0; i < clients.size(); i++)
{
DataOutputStream oo = new DataOutputStream(clients.get(i).getOutputStream());
oo.writeBytes(st);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
input.start();
}
public static void main(String[] args) throws IOException {
Server2 server = new Server2();
}
}
和客户端类:
public class Client2 {
final public static String host = "localhost";
final public static int port = 5000;
Socket socket;
DataInputStream in;
DataOutputStream ou;
Scanner chat;
boolean run;
String name;
public Client2(String n) throws IOException {
name = n ;
socket = new Socket(host , port);
System.out.println("Connection Successful");
run = true;
runOutput();
}
public void runOutput() {
Thread input = new Thread(new Runnable() {
public void run() {
while (run) {
try {
in = new DataInputStream(socket.getInputStream());
String s = in.readLine();
System.out.println(s);
if(chat.nextLine().compareTo("QUIT") == 0)
run = false;
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
input.start();
Thread t = new Thread(new Runnable() {
public void run() {
while (run) {
try {
ou = new DataOutputStream(socket.getOutputStream());
chat = new Scanner(System.in);
ou.writeBytes(name + " says :" + chat.nextLine() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
public static void main(String[] args) throws IOException {
Client2 client = new Client2("Ahmed");
}
}
【问题讨论】:
-
请发布您遇到的错误。另外,据我所知,您调用
runOutput()一次,并且没有循环,这意味着s = ss.accept()只会被调用一次 -
看看我编辑的答案。希望对你有所帮助
标签: java client-server chat