62,628
社区成员
发帖
与我相关
我的任务
分享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);
}
}
}