我正在用Java创建一个聊天系统。它不会抛出任何错误或任何东西,我无法看到任何我做错的事情,但当我尝试向服务器发送内容时,却没有收到。
服务器:
package net.murplyx.chatserver;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Main {
public static ServerSocket server;
public static ArrayList<Socket> clients = new ArrayList<Socket>();
public static ArrayList<String> messages = new ArrayList<String>();
public static void main(String[] args) throws Exception {
server = new ServerSocket(1234);
while (true) {
Socket c;
while ((c = server.accept()) != null) {
clients.add(c);
}
for (int i = clients.size() - 1; i > 0; i--) {
c = clients.get(i);
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
if (in.ready()) {
messages.add(in.readLine());
}
}
for (int i = clients.size() - 1; i > 0; i--) {
c = clients.get(i);
PrintWriter out = new PrintWriter(c.getOutputStream());
for (int j = 0; j < messages.size(); j++) {
String m = messages.get(j);
out.println(m);
}
}
messages.clear();
}
}
}
客户端:
package net.murplyx.chatclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static Socket socket;
public static void main(String[] args) throws Exception {
socket = new Socket("localhost", 1234);
while (true) {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if (in.ready()) {
System.out.println(in.readLine());
}
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String ln = input.readLine();
if (ln != null) {
out.println(ln);
}
}
}
}