问题描述
这是我的服务器代码:importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Map;importjava.util.Scanner;importjava.util.concurrent.ConcurrentHashMap;publicclassServer{finalintreceive_port=8008;booleanstarted=false;privateintcount=0;BufferedWriterbw;Filewriterfile;PrintWriteros=null;ConcurrentHashMap<Integer,Socket>clients=newConcurrentHashMap<Integer,Socket>();privateStringfilePath;ServerSocketserver=null;Socketsocket=null;publicvoidsetFilePath(StringfilePath){this.filePath=filePath;}publicServer()throwsException{newThread(newListenClient()).start();}classListenClientimplementsRunnable{publicvoidrun(){try{ServerSocketserver=newServerSocket(8008);while(true){Socketsocket=server.accept();count++;clients.put(count,socket);System.out.println("客户端"+count+"已经连接");MyThreadt=newMyThread(socket,count);MyThreadTwott=newMyThreadTwo(socket,count);t.start();tt.start();}}catch(Exceptione){System.out.println("连接异常!~~~");System.out.println(e.toString());}}}classMyThreadextendsThread{Socketsockett=null;BufferedReaderbuff=null;privateIntegerid;publicMyThread(Socketsocket,Integerid){sockett=socket;this.id=id;}publicvoidrun(){while(true){for(Map.Entry<Integer,Socket>client:clients.entrySet()){try{BufferedWriterwrite=newBufferedWriter(newOutputStreamWriter(client.getValue().getOutputStream()));Socketsocket=client.getValue();InputStreaminput=socket.getInputStream();byte[]by=newbyte[10];input.read(by);Stringbyy=newString(by);if(!byy.equals("")){byy.trim();System.out.println(byy);write.flush();}catch(Exceptione){clients.remove(client.getKey());System.out.println(client.getKey()+"isclosed");continue;}}}}}classMyThreadTwoextendsThread{Socketsockett=null;BufferedReaderbuff=null;privateIntegerid;publicMyThreadTwo(Socketsocket,Integerid){sockett=socket;this.id=id;}publicvoidrun(){while(true){Scannerscan=newScanner(System.in);Stringtmp="";tmp=scan.nextLine();for(Map.Entry<Integer,Socket>client:clients.entrySet()){try{BufferedWriterwrite=newBufferedWriter(newOutputStreamWriter(client.getValue().getOutputStream()));write.write(tmp+"n");//System.out.println("senddatato:"+client.getKey()+"client");write.flush();}catch(Exceptione){e.printStackTrace();}}}}}//文本写入publicvoidwriteFile(Stringpath,Stringcontent,booleanappend){Filewritefile;try{booleanaddStr=append;writefile=newFile(path);FileWriterfw=newFileWriter(writefile,addStr);PrintWriterpw=newPrintWriter(fw);bw=newBufferedWriter(fw);fw.write(content);pw.println("n");pw.println("n");fw.flush();fw.close();}catch(Exceptionex){ex.printStackTrace();}}publicstaticvoidmain(String[]args)throwsException{newServer();}}