java基础-网络编程(Socket)技术选型入门之NIO技术

                                         作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

 

一.传统的网络编程

1>.编写socket通信的MyServer,使用分线程完成和每个client的通信。

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:y1053419035@qq.com
 5 */
 6 package cn.org.yinzhengjie.socket;
 7 
 8 import java.io.OutputStream;
 9 import java.net.InetSocketAddress;
10 import java.net.ServerSocket;
11 import java.net.Socket;
12 
13 public class MyServer {
14     public static void main(String[] args) throws Exception {
15         //服务器套接字
16         ServerSocket ss = new ServerSocket(8888) ;
17         while(true){
18             //接受连接,
19             System.out.println("正在接受连接.....");
20             Socket sock = ss.accept();
21             new CommThread(sock).start();
22         }
23     }
24 }
25 
26 /**
27  * 服务器和每个客户端的通信线程
28  */
29 class CommThread extends Thread{
30     private Socket sock;
31 
32     public CommThread(Socket sock){
33         this.sock = sock ;
34     }
35 
36     public void run() {
37         try {
38             //获取远程地址和端口
39             InetSocketAddress addr = (InetSocketAddress) sock.getRemoteSocketAddress();
40             int port = addr.getPort();
41             String ip = addr.getAddress().getHostAddress();
42             System.out.printf("有人连接进来了!! : %s , %d\r\n", ip, port);
43 
44             //向客户端发送消息
45             int index = 0;
46             OutputStream out = sock.getOutputStream();
47             while (true) {
48                 index ++ ;
49                 out.write(("yinzhengjie" + index + "\r\n").getBytes());
50                 out.flush();
51                 Thread.sleep(1000);
52             }
53         } catch (Exception e) {
54             e.printStackTrace();
55         }
56     }
57 }
MyServer.java 文件内容

相关文章:

  • 2021-08-06
  • 2021-08-16
  • 2021-07-18
  • 2022-02-03
  • 2021-12-12
  • 2021-04-12
  • 2021-11-09
猜你喜欢
  • 2021-07-24
  • 2022-12-23
  • 2021-08-19
  • 2021-11-02
  • 2021-06-19
  • 2021-12-22
  • 2022-12-23
相关资源
相似解决方案