客户端代码如下:
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
Socket client=new Socket("localhost", 7978);
BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
//pw.println("wefwfwf");
//pw.flush();
String da=null;
while((da=br.readLine())!=null) {
System.out.println(da);
}
}
}
服务器代码如下:
public class Server implements Runnable{
private static ServerSocket serverSocket;
private static List<Socket> clients;
private static PrintWriter pw;
private static String msg;
private BufferedReader br;
private static List<String> msgs;
public  Server() throws IOException {
clients=new ArrayList<>();;
serverSocket=new ServerSocket(7978);
msgs=new ArrayList<>();
msg=null;
}
@Override
public void run() {
try {
while(true) {
// System.out.println("");   必须加这个???
if(clients.size()!=0) {
if(msgs.size()!=0) {
for(Socket client:clients) {
pw=new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
pw.println(msgs.get(0));
pw.flush();
}
msgs.remove(0);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
new Thread(new Server()).start();
while(true) {
Socket client=serverSocket.accept();
msg=client.toString()+"is coming";
msgs.add(msg);
clients.add(client); 
}
}
}写了一个小的socket多线程通信demo,可以看到我注释的那个地方,为什么必须加一个这个东西,不然就阻塞了。讲道理我的PrintWrirter用的是println啊,不应该存在回车的问题的,死活想不明白,请大神执教