Java学习系列(十七)Java面向对象之开发聊天工具

TCP通信
Socket --相当于“虚拟链路两端的插座”。Socket负责完成通信。
ServerSocket --它只负责“接收”连接。它用于产生Socket。

服务器端编程
1) 创建ServerSocket 对象,该对象负责“接收”连接。
2) 如果客户端有连接,ServerSocket 对象调用accept()方法返回一个Socket。
3) 通过IO流读取对方的信息,也可向对方发送数据。

 

客户端编程
1) new Socket()来建立与远程服务器的连接。
2) 通过IO流读取对方的信息,也可向对方发送数据。

举列说明1(简单通信):

 

Java代码   收藏代码
  1. /** 
  2.  * @author lhy 
  3.  * @description 服务器端 
  4.  */  
  5. public class ServerTest {  
  6.     public static void main(String[] args) {  
  7.         PrintStream ps = null;  
  8.         try {  
  9.             // ServerSocket只负责“接收”连接,20000为端口号(标识该应用程序)  
  10.             ServerSocket ss = new ServerSocket(20000);  
  11.             System.out.println("服务器端等待连接...");  
  12.             // 接收连接,它会阻塞线程  
  13.             Socket socket = ss.accept();  
  14.   
  15.             // ----------------------下面统一面向IO编程--------------------------//  
  16.             ps = new PrintStream(socket.getOutputStream());  
  17.             ps.println("ServerTest你好");  
  18.         } catch (IOException e) {  
  19.             e.printStackTrace();  
  20.         } finally {  
  21.             ps.close();  
  22.         }  
  23.     }  
  24.   
  25. }  

 

Java代码   收藏代码
  1. /** 
  2.  * @author lhy 
  3.  * @description 客户端 
  4.  */  
  5. public class ClientTest {  
  6.     public static void main(String[] args) {  
  7.         BufferedReader br = null;  
  8.         try {  
  9.             Socket socket = new Socket("192.168.0.8"20000);  
  10.   
  11.             // ----------------------下面统一面向IO编程--------------------------//  
  12.             br = new BufferedReader(new InputStreamReader(socket  
  13.                     .getInputStream()));  
  14.             String line = null;  
  15.             while ((line = br.readLine()) != null) {  
  16.                 System.out.println(line);  
  17.             }  
  18.         } catch (IOException e) {  
  19.             e.printStackTrace();  
  20.         } finally {  
  21.             try {  
  22.                 br.close();  
  23.             } catch (IOException e) {  
  24.                 e.printStackTrace();  
  25.             }  
  26.         }  
  27.     }  
  28. }  

举列说明2(控制台多人聊天):

 

服务器端:

 

Java代码   收藏代码
  1. public class ServerTest {  
  2.     static Set<Socket> clients = Collections  
  3.             .synchronizedSet(new HashSet<Socket>());  
  4.   
  5.     public static void main(String[] args) {  
  6.         ServerSocket ss = null;  
  7.         try {  
  8.             ss = new ServerSocket(20000);  
  9.             System.out.println("服务器端等待连接...");  
  10.             while (true) {  
  11.                 // 接收连接,它会阻塞线程  
  12.                 Socket socket = ss.accept();  
  13.                 clients.add(socket);  
  14.                 // 启动线程  
  15.                 new ServerThread(socket).start();  
  16.             }  
  17.         } catch (IOException e) {  
  18.             e.printStackTrace();  
  19.         } finally {  
  20.             try {  
  21.                 ss.close();  
  22.             } catch (IOException e) {  
  23.                 e.printStackTrace();  
  24.             }  
  25.         }  
  26.     }  
  27. }  
  28.   
  29. // 单独封装一个线程类  
  30. class ServerThread extends Thread {  
  31.     private Socket socket;  
  32.   
  33.     public ServerThread(Socket socket) {  
  34.         this.socket = socket;  
  35.     }  
  36.   
  37.     @Override  
  38.     public void run() {  
  39.         BufferedReader br = null;  
  40.         try {  
  41.             while (true) {  
  42.                 // ----------------------下面统一面向IO编程--------------------------//  
  43.                 br = new BufferedReader(new InputStreamReader(socket  
  44.                         .getInputStream()));  
  45.                 String line = null;  
  46.                 while ((line = br.readLine()) != null) {  
  47.                     for (Socket s : ServerTest.clients) {  
  48.                         PrintStream ps = new PrintStream(s.getOutputStream());  
  49.                         ps.println(line);// 输出各个客户端对应的Socket  
  50.                     }  
  51.                 }  
  52.             }  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         } finally {  
  56.             try {  
  57.                 br.close();  
  58.             } catch (IOException e) {  
  59.                 e.printStackTrace();  
  60.             }  
  61.         }  
  62.     }  
  63. }  

客户端:

 

 

Java代码   收藏代码
  1. public class ChatServer {  
  2.     // 定义一个线程安全的Set集合  
  3.     public static Set<Socket> clients = Collections  
  4.             .synchronizedSet(new HashSet<Socket>());  
  5.   
  6.     public static void main(String[] args) throws IOException {  
  7.         // ServerSocket只负责“接受”连接,不能通信  
  8.         // 该服务器程序就在30002端口监听  
  9.         ServerSocket ss = new ServerSocket(20000);  
  10.         System.out.println("服务器等待连接...");  
  11.         while (true) { // 这样保证每个客户端有一条线程  
  12.             // 接受连接。它会阻塞线程  
  13.             Socket socket = ss.accept();// 只要连接成功,它会返回socket  
  14.             clients.add(socket);// 每次客户端连接进来,就将该客户端添加到clients集合中  
  15.             System.out.println("当前用户数量:" + clients.size());  
  16.             new ServerThread(socket).start();  
  17.         }  
  18.     }  
  19. }  
  20.   
  21. class ServerThread extends Thread {  
  22.     private Socket socket;  
  23.   
  24.     public ServerThread(Socket socket) {  
  25.         this.socket = socket;  
  26.     }  
  27.   
  28.     @Override  
  29.     public void run() {  
  30.         // -----原來读文件,现在改为读网络,只要改节点  
  31.         try {  
  32.             BufferedReader socketBr = new BufferedReader(new InputStreamReader(  
  33.                     socket.getInputStream()));  
  34.             String line = null;// line代表从网络中读取数据  
  35.             while ((line = socketBr.readLine()) != null) {  
  36.                 for (Iterator<Socket> it = ChatServer.clients.iterator(); it  
  37.                         .hasNext();) {  
  38.                     Socket s = it.next();  
  39.                     try {  
  40.   
  41.                         PrintStream ps = new PrintStream(s.getOutputStream());  
  42.                         ps.println(line);// 输出到各客户端对应的socket  
  43.                     } catch (SocketException ex) {  
  44.                         it.remove();// 捕获到该socket的异常,即表明Socket已经断开  
  45.                                                 System.out.println("当前用户数量:" + ChatServer.clients.size());  
  46.                         // ex.printStackTrace();  
  47.                     }  
  48.                 }  
  49.             }  
  50.         } catch (SocketException se) {  
  51.             ChatServer.clients.remove(socket);  
  52.                         System.out.println("当前用户数量:" + ChatServer.clients.size());   
  53.         } catch (Exception e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57. }  

小结:

 

System.in :读取键盘输入。包装方法:BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

socket.getInputStream():读取网络。包装方法:BufferedReadersocketBr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

socket.getOutputStream():写入(输出到)网络。包装方法:PrintStream socketOut = new PrintStream(socket.getOutputStream());

System.out:输出到屏幕。

下面以之前IO讲的一张图来结束:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值