package huangfeng.TongXin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; /* * 基于TCP协议的Socket通信,实现用户登录 * 服务器端 */ public class Server { public static void main(String[] args) { try { //创建一个Socket服务器端,即ServerSocket,指定绑定端口,并监听此端口 //创建ServerSocket的实例 ServerSocket serverSocket = new ServerSocket(9999); System.out.println("******服务器即将启动,等待客户端的连接******"); //调用accept()方法开始监听,等待服务器的连接 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(); //关闭相关资源 br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
package huangfeng.TongXin; import java.io.IOException; 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", 9999); //获取输出流,向服务器端发送信息 OutputStream os = socket.getOutputStream();//字节输出流 //将输出流包装为打印流 PrintWriter pw = new PrintWriter(os); pw.write("用户名:huangfeng ; 密码:8888"); pw.flush(); socket.shutdownOutput();//关闭输出流 //关闭相关资源 pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
******服务器即将启动,等待客户端的连接******
我是服务器,客户端说:用户名:huangfeng ; 密码:8888
java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:115)
at java.io.BufferedReader.readLine(BufferedReader.java:310)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at huangfeng.TongXin.Server.main(Server.java:31)
ziom
lindajia
相关分类