当前位置: 首页 > news >正文

JavaSE 网络编程

什么是网络编程

计算机与计算机之间通过网络进行数据传输

两种软件架构

 

 网络编程3要素

IP

IPv4

 IPv6

 

 

 

    @Testpublic void test01() throws UnknownHostException {
//        InetAddress.getByName 可以是名字或ipInetAddress address = InetAddress.getByName("LAPTOP-7IJTG2U2");System.out.println(address);String hostName = address.getHostName();System.out.println(hostName);String ip = address.getHostAddress();System.out.println(ip);}

端口号

协议 

OSI参考模型

TCP/IP协议

 

 

UDP

发送数据,接收数据

代码

    /*54321端口发送数据到12345端口,从12345端口取出数据*/@Testpublic void UDP_Send() throws IOException {//1.创建DatagramSocket对象(快递公司)//空参:绑定随机端口DatagramSocket ds = new DatagramSocket(54321);//2.打包数据byte[] data="测试UDP".getBytes();InetAddress address = InetAddress.getByName("LAPTOP-7IJTG2U2");int port=12345;DatagramPacket dp = new DatagramPacket(data,data.length,address,12345);//发送数据,释放资源ds.send(dp);//向名为“LAPTOP-7IJTG2U2”的计算机的12345端口发送数据ds.close();}@Testpublic void UDP_Receive() throws IOException {//创建DatagramSocket对象,绑定端口12345,因为数据被发送到12345端口DatagramSocket ds = new DatagramSocket(12345);InetAddress address = InetAddress.getByName("LAPTOP-7IJTG2U2");byte[] bytes = new byte[1024];DatagramPacket dp = new DatagramPacket(bytes,bytes.length);System.out.println("12345端口等待接收数据中");ds.receive(dp);System.out.println("12345端口接收到数据");byte[] data = dp.getData();String s = new String(data,0,dp.getLength());System.out.println("从ip:"+dp.getAddress()+"的"+dp.getPort()+"端口获取到数据:"+s);}

先运行UDP_Receive,会阻塞在ds.receive ,再运行UDP_Send发送数据

运行结果

12345端口等待接收数据中
12345端口接收到数据
从ip:/192.168.123.1的54321端口获取到数据:测试UDPProcess finished with exit code 0

UDP案例:聊天室 

需求

发送(聊天室里面的人)

public class RoomSend {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket();Scanner sc = new Scanner(System.in);InetAddress address = InetAddress.getByName("127.0.0.1");int port=12345;while (true){System.out.println("请输入:");String str = sc.next();if("886".equals(str)){break;}byte[] bytes = str.getBytes();DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);ds.send(dp);}ds.close();}
}

接收 (聊天室)

public class RoomReceive {public static void main(String[] args) throws IOException {DatagramSocket ds = new DatagramSocket(12345);byte[] bytes = new byte[1024];DatagramPacket dp = new DatagramPacket(bytes, 0,bytes.length);while (true){ds.receive(dp);System.out.println(dp.getAddress()+"--"+dp.getPort()+"--"+new String(dp.getData(),0,dp.getLength()));}}
}

 允许创建多个RoomSend

 

测试 

 

 

 

TCP

发送数据,接收数据

服务端

public class Server {public static void main(String[] args) throws IOException {//1.创建ServerSocket对象ServerSocket ss = new ServerSocket(10000);//2.监听客户端的链接,没有客户端链接会一直卡在这里,有客户端连接返回socket对象Socket socket = ss.accept();//3.获取输入流,读数据int b;BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));while ((b=br.read())!=-1){System.out.print((char)b);}//4.释放资源br.close();socket.close();//ss.close();   //客户端不关闭}
}

 客户端

public class Client {public static void main(String[] args) throws IOException {//1.创建socket对象,连接不到服务器的端口10000会报错Socket socket = new Socket("127.0.0.1", 10000);//2.获取socket对象的输出流,输出数据OutputStream os = socket.getOutputStream();os.write("我测".getBytes());//3.释放资源os.close();socket.close();}
}

TCP的三次握手和四次挥手

三次握手

四次挥手

练习

接收并反馈信息

上传文件

 

服务端 

public class Server {public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(10000);Socket socket = ss.accept();InputStream is = socket.getInputStream();BufferedInputStream bis = new BufferedInputStream(is);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\java_workspace\\demo3\\src\\main\\java\\com\\example\\upload\\copy.png"));int len;byte[] bytes = new byte[1024];while ((len=bis.read(bytes))!=-1){bos.write(bytes,0,len);}bos.close();bis.close();socket.close();ss.close();System.out.println("传输完成");}
}

客户端

public class Client {public static void main(String[] args) throws IOException {FileInputStream fis = new FileInputStream(new File("D:\\java_workspace\\demo3\\src\\main\\java\\com\\example\\upload\\img.png"));BufferedInputStream bis = new BufferedInputStream(fis);int len;byte[] bytes = new byte[1024];Socket socket = new Socket("127.0.0.1", 10000);OutputStream os = socket.getOutputStream();while ((len= fis.read(bytes))!=-1){os.write(bytes,0,len);}fis.close();socket.shutdownOutput();os.close();socket.close();}
}

上传文件(线程版)

服务端

public class TCPServer {public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(10000);while (true){Socket socket = ss.accept();new Thread(new MyRunnable(socket)).start();}}
}
public class MyRunnable implements Runnable{private Socket socket;public MyRunnable(Socket socket) {this.socket = socket;}@Overridepublic void run() {try {InputStream is = socket.getInputStream();BufferedInputStream bis = new BufferedInputStream(is);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\java_workspace\\demo3\\src\\main\\java\\com\\example\\upload\\" + UUID.randomUUID().toString().replace("-", "") + ".png"));int len;byte[] bytes = new byte[1024];while ((len = bis.read(bytes)) != -1) {bos.write(bytes, 0, len);}bos.close();bis.close();socket.close();System.out.println("传输完成");} catch (IOException e) {e.printStackTrace();}}
}

 客户端

public class TCPClient {public static void main(String[] args) throws IOException, InterruptedException {FileInputStream fis = new FileInputStream(new File("D:\\java_workspace\\demo3\\src\\main\\java\\com\\example\\upload\\img.png"));BufferedInputStream bis = new BufferedInputStream(fis);int len;byte[] bytes = new byte[1024];Socket socket = new Socket("127.0.0.1", 10000);OutputStream os = socket.getOutputStream();while ((len = fis.read(bytes)) != -1) {os.write(bytes, 0, len);}Thread.sleep(5000);fis.close();socket.shutdownOutput();os.close();socket.close();}
}

上传文件(线程池版)

服务端

public class TCPServer {private static ThreadPoolExecutor myThreadPool = new ThreadPoolExecutor(4,//核心线程数17,//最大线程数1,//空闲线程最大存活时间TimeUnit.MINUTES,//时间单位new ArrayBlockingQueue<>(2),//长度为3的等待队列Executors.defaultThreadFactory(),//创建线程工厂new ThreadPoolExecutor.AbortPolicy()//设置拒绝策略:丢弃任务并抛出异常);public static void main(String[] args) throws IOException {ServerSocket ss = new ServerSocket(10000);while (true){Socket socket = ss.accept();TCPServer.myThreadPool.submit(new MyRunnable(socket));
//            new Thread(new MyRunnable(socket)).start();}}
}

客户端和MyRunnable同上

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【学习笔记】Day 12
  • 11 Radiobutton组件
  • C# 通过代码开启自动设置时间和自动设置时区选项
  • 力扣 | 动态规划 | 状态机 | 买卖股票 | 买卖股票的最佳时机
  • MVI、MVVM、MVP的对比
  • 已解决:java.lang.UnsupportedClassVersionError 异常的正确解决方法,亲测有效!!!
  • 肿瘤细胞表皮生长因子EGFR靶向肽;GE11;YHWYGYTPQNVI
  • fastjson(autoType)反序列化漏洞
  • 经典结构Transformer解读
  • 本地访问不到公网redis的解决方法
  • 【Python】Python单元测试
  • Docker重启命令
  • stm32—中断机制
  • GSON转换将Long类型转换Double导致精度丢失的问题排查
  • Redis:查询是否包含某个字符/字符串之二
  • 《网管员必读——网络组建》(第2版)电子课件下载
  • ECMAScript6(0):ES6简明参考手册
  • IDEA常用插件整理
  • Linux快速复制或删除大量小文件
  • redis学习笔记(三):列表、集合、有序集合
  • scrapy学习之路4(itemloder的使用)
  • zookeeper系列(七)实战分布式命名服务
  • 简单易用的leetcode开发测试工具(npm)
  • 今年的LC3大会没了?
  • 离散点最小(凸)包围边界查找
  • 想写好前端,先练好内功
  • Semaphore
  • 关于Android全面屏虚拟导航栏的适配总结
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • #if和#ifdef区别
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • #知识分享#笔记#学习方法
  • ${factoryList }后面有空格不影响
  • ( 用例图)定义了系统的功能需求,它是从系统的外部看系统功能,并不描述系统内部对功能的具体实现
  • (1)SpringCloud 整合Python
  • (Java入门)学生管理系统
  • (Oracle)SQL优化基础(三):看懂执行计划顺序
  • (第30天)二叉树阶段总结
  • (附源码)springboot家庭装修管理系统 毕业设计 613205
  • (附源码)ssm高校社团管理系统 毕业设计 234162
  • (论文阅读30/100)Convolutional Pose Machines
  • (每日持续更新)jdk api之FileFilter基础、应用、实战
  • (三) prometheus + grafana + alertmanager 配置Redis监控
  • (顺序)容器的好伴侣 --- 容器适配器
  • (算法)大数的进制转换
  • *_zh_CN.properties 国际化资源文件 struts 防乱码等
  • *算法训练(leetcode)第四十七天 | 并查集理论基础、107. 寻找存在的路径
  • .Net Core缓存组件(MemoryCache)源码解析
  • .NET/MSBuild 中的发布路径在哪里呢?如何在扩展编译的时候修改发布路径中的文件呢?
  • .Net+SQL Server企业应用性能优化笔记4——精确查找瓶颈
  • .net解析传过来的xml_DOM4J解析XML文件
  • @AutoConfigurationPackage的使用
  • @Autowired 和 @Resource 区别的补充说明与示例
  • @autowired注解作用_Spring Boot进阶教程——注解大全(建议收藏!)
  • @converter 只能用mysql吗_python-MySQLConverter对象没有mysql-connector属性’...