代码运行出现错误
SEVER: package com.imooc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /* * 基于TCP的Socket的通信 * 服务器端 */ public class Sever { public static void main(String[] args) { // TODO Auto-generated method stub try { ServerSocket serversocket=new ServerSocket(8888); 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(); is.close(); isr.close(); br.close(); os.close(); pw.close(); serversocket.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
client:
package com.imooc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; /* * 基于TCP的Socket的通信 * 客户端 */ public class Client { public static void main(String[] args) { // TODO Auto-generated method stub try { InetAddress address=InetAddress.getLocalHost(); Socket socket=new Socket(address.getHostAddress(),8888); OutputStream os=socket.getOutputStream();//输出流 PrintWriter pw=new PrintWriter(os);//将输出流转换为打印流 pw.write("用户名:可心;密码是:1234"); pw.flush(); socket.shutdownOutput();//关闭输出流 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(); os.close(); pw.close(); is.close(); isr.close(); br.close(); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行结果