package com.test; /* * server类 */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { //创建ServerSocket对象 ServerSocket server=new ServerSocket(8888); System.out.println("服务器等待连接中....."); //调用accept()开始监听,等待客户端的连接 Socket s=server.accept(); //获得输入流,来读取客户信息 InputStream in=s.getInputStream();//字节输入流 InputStreamReader isr=new InputStreamReader(in);//将字节流包装为字符流 BufferedReader br=new BufferedReader(isr);//为输入流添加缓冲 String info=null; while((info=br.readLine())!=null){ System.out.println("******服务器开始读取*****"); System.out.println("我是服务器,客户端说:"+info); info=br.readLine(); } //添加输出流,为客户端输出信息 OutputStream out=s.getOutputStream(); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(out)); bw.write("欢迎您!!!"); bw.flush(); //关闭资源 out.close(); bw.close(); server.close(); in.close(); isr.close(); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.test; /* * client类 */ 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.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { try { //创建Socket对象 Socket socket=new Socket("localhost", 8888); //获取输出流 OutputStream out=socket.getOutputStream(); PrintWriter pw=new PrintWriter(out); pw.write("ueser:tom;key:123"); pw.flush(); //添加输出流 InputStream in=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(in)); String info=null; while((info=br.readLine())!=null){ System.out.println("我是客户端,服务器端说:"+info); } //关闭资源 in.close(); br.close(); socket.close(); out.close(); pw.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
client控制台就显示:服务器等待连接中.....
server控制台没反应
解决办法:
在Server类的第33、34行像讲师一样插入这句代码:
s.shutdownInput();
在Server类的原第38、39行像讲师一样插入这句代码:
s.shutdownOutput();
在Client类的第24、25行像讲师一样插入这句代码:
socket.shutdownOutput();
在Client类的原第31、32行像讲师一样插入这句代码:
socket.shutdownInput();
p.s. 建议把Server类的第30行代码放到28或29行之前。