public class Server { public static void main(String[] args) { try { // 创建一个服务端socket ServerSocket serverSocket = new ServerSocket(8888); //调用accept方法 System.out.println("*********服务端即将启动*****"); Socket socket = serverSocket.accept(); //获取输入流,并读取客户端信息 InputStream is =socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String info = null; while((info = br.readLine())!=null){ System.out.println("-----服务器端,客户端:"+info); } socket.shutdownInput(); //获取输出流 OutputStream os=socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("欢迎登陆"); pw.flush(); socket.shutdownOutput(); //关闭资源 pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }public class Client { public static void main(String[] args) { try { //创建客户端 Socket socket = new Socket("localhost",8888); //获取输出流 OutputStream os=socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("用户名:admin;密码:1111"); pw.flush(); socket.shutdownOutput(); //获取输入流 InputStream is =socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String info = null; while((info = br.readLine())!=null){ System.out.println("-----客户端,服务端:"+info); } //关闭资源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
写错了 是不用关闭输入输出流 直接关闭SOCKET就可以
还有,不用关闭输出流,在关闭socket的时候就会关闭输出流
那些输入输出流 还有socket的关闭的顺序要对。先开的最后关,最后开的最先关!
在连接断开之后,在进行读写,导致该异常