Java中使用Socket实现服务器端和客户端通讯
创建服务器端serverSocket
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStream; 6 import java.io.PrintWriter; 7 import java.net.ServerSocket; 8 import java.net.Socket; 9 10 /** 11 * 服务端 12 * @author Administrator 13 * 14 */ 15 public class Server { 16 17 public static void main(String[] args) throws IOException { 18 //创建一个服务器端socket,指定绑定的端口号,并监听此端口 19 ServerSocket serverSocket = new ServerSocket(8888); 20 //调用accept()方法开始监听,等待客户端的连接 21 System.out.println("**********服务器即将启动,等待客户端的连接*************"); 22 Socket socket = serverSocket.accept(); 23 //获取输入流,并读取客户端信息 24 InputStream inp = socket.getInputStream(); 25 //把字节流转换成字符流 26 InputStreamReader isr = new InputStreamReader(inp); 27 //为字符流增加缓冲区 28 BufferedReader bfr = new BufferedReader(isr); 29 String info = null; 30 while((info=bfr.readLine())!=null){//循环读取数据 31 System.out.println("我是服务器,客户端说:"+info); 32 } 33 socket.shutdownInput();//关闭输入流 34 //向客户端传递的信息 35 OutputStream ots = socket.getOutputStream(); 36 PrintWriter pw = new PrintWriter(ots); 37 pw.write("欢迎登陆"); 38 pw.flush(); 39 40 //关闭资源 41 pw.close(); 42 ots.close(); 43 bfr.close(); 44 isr.close(); 45 inp.close(); 46 socket.close(); 47 serverSocket.close(); 48 49 } 50 51 }
创建客户端socket
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStream; 6 import java.io.PrintWriter; 7 import java.net.Socket; 8 import java.net.UnknownHostException; 9 10 /** 11 * 客户端 12 * @author Administrator 13 * 14 */ 15 public class Client { 16 17 public static void main(String[] args) { 18 try { 19 //创建一个客户端socket 20 Socket socket = new Socket("localhost",8888); 21 //向服务器端传递信息 22 OutputStream ots = socket.getOutputStream(); 23 PrintWriter pw = new PrintWriter(ots); 24 pw.write("用户名:admin;密码:123"); 25 pw.flush(); 26 //关闭输出流 27 socket.shutdownOutput(); 28 //获取服务器端传递的数据 29 InputStream is = socket.getInputStream(); 30 InputStreamReader isr = new InputStreamReader(is); 31 BufferedReader br = new BufferedReader(isr); 32 String info = null; 33 while((info=br.readLine())!=null){ 34 System.out.println("我是客户端,服务器说:"+info); 35 } 36 //关闭资源 37 br.close(); 38 isr.close(); 39 is.close(); 40 pw.close(); 41 ots.close(); 42 socket.close(); 43 } catch (UnknownHostException e) { 44 e.printStackTrace(); 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } 48 } 49 50 }
先启动服务器端,再启动客户端
服务器端打印结果为
**********服务器即将启动,等待客户端的连接*************
我是服务器,客户端说:用户名:admin;密码:123
客户端打印结果
我是客户端,服务器说:欢迎登陆