基础入门之网络编程
2021/6/16 20:51:37
本文主要是介绍基础入门之网络编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
网络编程
1.1、概述
信件:
计算机网络:
计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
网络编程的目的:
无线电台(早期)…传播交流信息,数据交换,通信。
想要达到这个效果需要什么:
- 如何准确的定位网络上的一台主机: 192.168.16.125:端口,定位到这个计算机上的某个资源。
- 找到主机后,如何传输数据?
Javaweb:网页编程 B/S
网络编程:TCP/IP C/S
1.2、网络通信的要素
如何实现网络的通信?
通信双方的地址:
- IP
- 端口号
- 192.168.16.125:5900
规则:网络通信的协议
TCP/IP参考模型:
1.3、IP
IP地址:InetAddress
-
唯一定位一台网络上的计算机
-
127.0.0.1:本机的localhost
-
IP地址的分类
-
ipv4/ipv6
- IPV4 地址:127.0.0.1 ,4个字节组成。 ,端口号 0-255, 2011年用完了。
- IPV6 地址:fe80::915d:470e:d522:4339%16 ,128位。8个无符号整数
-
公网(互联网使用)–私网(局域网使用)
- ABCD类地址
- 192.168.xxx.xxx 就是专门给组织内部使用的,是局域网。
-
-
域名:记忆IP问题
- IP:www.vip.com
import java.net.InetAddress; import java.net.UnknownHostException; //测试IP public class TestDemo01 { public static void main(String[] args) { try { //查询本机地址 InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress1); InetAddress inetAddress3 = InetAddress.getByName("localhost"); System.out.println(inetAddress3); InetAddress inetAddress4 = InetAddress.getLocalHost(); System.out.println(inetAddress4); //查询网站IP地址 InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com"); System.out.println(inetAddress2); //常用的方法 System.out.println(inetAddress2.getAddress()); System.out.println(inetAddress2.getCanonicalHostName());//规范的名称 System.out.println(inetAddress2.getHostAddress());//ip System.out.println(inetAddress2.getHostName());//域名,或者自己电脑的名字 } catch (UnknownHostException e) { e.printStackTrace(); } } }
1.4、端口
端口表示计算机上的一个程序的进程。一个端口就是一个进程。
-
不同的进程有不同的端口号,端口号不能冲突(重复);用来区分软件。
-
被规定 0–65535
-
TCP/UDP:65535*2 tcp:80 ,udp:80 单个协议下,端口号不能冲突。
-
端口分类
-
公有端口 0-1023
- HTTP协议:80(端口号)
- HTTPS协议:443(端口号)
- FTP:21
- Telent:23
-
程序注册端口: 1024-49151 ,分配用户或者程序
- Tomcat:8080
- MySQL:3306
- Oracle:1521
-
动态、私有:49152-66535
netstat -ano #查看所有端口 netstat -ano|findstr "5900" #查看指定端口 tasklist|findstr "8696" #查看指定端口的进程 ctrl+shift+esc #快捷键打开用户管理器
-
import java.net.InetSocketAddress; public class TestInetSocketAddressDemo { public static void main(String[] args) { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080); System.out.println(socketAddress); InetSocketAddress socketAddress1 = new InetSocketAddress("localhost",8080); System.out.println(socketAddress1); //常用方法 System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getHostName()); System.out.println(socketAddress.getHostString()); System.out.println(socketAddress.getPort()); } }
1.5、通信协议
**网络通信协议:**速率、传输码率、代码结构、传输控制…
TCP/IP协议簇:实际上是一种协议
- TCP: 用户传输协议
- UDP: 用户数据报协议
- IP: 网络互连协议
TCP和UDP对比:
TCP:打电话
- 连接,稳定
三次握手
四次挥手
最少需要三次,保证稳定连接。 A:你愁啥? B:瞅你咋地? A:走一个!
- 客户端、服务端 :有界限
- 传输完成,释放连接,效率低
UDP:发短信
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管准备好没有,都会发送信息
- DDOS:洪水攻击!(饱和攻击)
1.6、TCP
客户端
- 连接服务器 Socket
- 发送消息
import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; //客户端 public class TestClientDemo01 { public static void main(String[] args) { Socket socket =null; OutputStream outputStream =null; try { //首先要知道服务器的IP 端口号 InetAddress inetAddress = InetAddress.getByName("localhost"); int port=8888; //建立以个socket连接 socket = new Socket(inetAddress,port); //输出信息 outputStream = socket.getOutputStream(); outputStream.write("迪迦,用你的奥特之光消灭它吧!".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { //关闭资源 if (outputStream!=null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
服务器端
- 建立服务的端口 ServerSocket
- 等待用户的连接 accept()
- 接收用户的消息
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //服务器端 public class TestServerDemo01 { public static void main(String[] args) { ServerSocket serverSocket =null; Socket socket =null; InputStream inputStream =null; ByteArrayOutputStream byteArrayOutputStream =null; try { //确定一个地址 serverSocket = new ServerSocket(8888); while (true){ //等待客户端的连接 socket = serverSocket.accept(); //读取客户端发送的消息 inputStream = socket.getInputStream(); /* byte[] buffer = new byte[1024]; int len; while ((len=inputStream.read(buffer))!=-1){ String msg = new String(buffer,0,len); System.out.println(msg); } */ //管道流 byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len=inputStream.read(buffer))!=-1){ byteArrayOutputStream.write(buffer,0,len); } System.out.println(byteArrayOutputStream.toString()); } } catch (IOException e) { e.printStackTrace(); }finally { //关闭资源 if (byteArrayOutputStream!=null){ try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket!=null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
文件上传
客户端
import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class TestClientDemo02 { public static void main(String[] args) throws Exception { //创建一个socket连接 Socket socket = new Socket(InetAddress.getByName("localhost"),8080); //输出流 OutputStream outputStream = socket.getOutputStream(); //文件读取 FileInputStream fileInputStream = new FileInputStream(new File("feng.jpg")); //IO流判断 byte[] buffer = new byte[1024]; int len; while ((len=fileInputStream.read(buffer))!=-1){ outputStream.write(buffer,0,len); } //通知服务器,已经传输完毕 socket.shutdownOutput();//已经上传完毕 //确认服务器端已经接收,然后断开连接 InputStream stream = socket.getInputStream(); //String byte[] ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer2 = new byte[1024]; int len2; while ((len2=stream.read(buffer2))!=-1){ byteArrayOutputStream.write(buffer2,0,len2); } System.out.println(byteArrayOutputStream.toString()); //关闭资源 byteArrayOutputStream.close(); stream.close(); fileInputStream.close(); outputStream.close(); socket.close(); } }
服务器端
import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TestServerDemo02 { public static void main(String[] args) throws Exception { //建立一个连接 ServerSocket serverSocket = new ServerSocket(8080); //accept接收 Socket socket = serverSocket.accept();//阻塞式监听 //输入流 InputStream is = socket.getInputStream(); //文件输出 FileOutputStream fileOutputStream = new FileOutputStream(new File("ggl.jpg")); //IO流 byte[] buffer = new byte[1024]; int len; while ((len=is.read(buffer))!=-1){ fileOutputStream.write(buffer,0,len); } //通知客户端已经接收了 OutputStream stream = socket.getOutputStream(); stream.write("搞定,结束了".getBytes()); //关闭资源 stream.close(); fileOutputStream.close(); is.close(); socket.close(); serverSocket.close(); } }
1.7、UDP
发短信:不需要连接,直接发送。
发送端:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; //不需要连接服务器 public class UdpClientDem01 { public static void main(String[] args) throws Exception { //建立一个socket连接 DatagramSocket datagramSocket = new DatagramSocket(); //创建一个包 String s="一起来飞车,加油植物大战僵尸"; InetAddress localhost = InetAddress.getByName("localhost"); int port=9090; //参数名称: 数据、数据的起始长度、发送到对方的ip和端口号 DatagramPacket datagramPacket = new DatagramPacket(s.getBytes(),0,s.getBytes().length,localhost,port); //发送信息 datagramSocket.send(datagramPacket); //关闭资源 datagramSocket.close(); } }
接收端:
import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpServerDemo01 { public static void main(String[] args) throws Exception { //建立一个连接 DatagramSocket socket = new DatagramSocket(9090); //建立一个包 byte[] bytes = new byte[1024]; DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length); //阻塞接收 socket.receive(packet); System.out.println(packet.getAddress().getHostAddress()); System.out.println(new String(packet.getData(),0,packet.getLength())); //关闭资源 socket.close(); } }
聊天
循环发送消息:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UdpSenderDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(8888); //准备数据 控制台读取 System.in BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true){ String data = reader.readLine();//数据 byte[] dataBytes = data.getBytes();//数据转化 DatagramPacket packet = new DatagramPacket(dataBytes,0,dataBytes.length,new InetSocketAddress("localhost",6666)); socket.send(packet); //退出判断 bb表示退出 if (data.equals("bb")){ break; } } //关闭资源 socket.close(); } }
循环接收消息:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(6666); while (true){ //准备接收包裹 byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,0,container.length); socket.receive(packet);//阻塞式接收包裹 //断开连接 结束语:bb byte[] data = packet.getData(); String receiveData = new String(data, 0, data.length); System.out.print(receiveData); if (receiveData.equals("bb")){ break; } } //关闭资源 socket.close(); } }
1.8、URL
统一资源定位符:定位资源的,定位互联网上的某一个资源。
DNS域名解析:www.baidu.com xxx.x…x…x
格式===> 协议://ip地址:端口号/项目名/资源
import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class UrlDown { public static void main(String[] args) throws Exception { //下载地址 URL url = new URL("https://m701.music.126.net/20210616182423/f21fe1179214b3d27f2b0ea638317388/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/9313927104/a809/a937/4553/134c850ec96faf0314c72b2680a96683.m4a"); //连接这个资源 http HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("3.m4a"); byte[] buffer = new byte[1024]; int len; while ((len=inputStream.read(buffer))!=-1){ fileOutputStream.write(buffer,0,len); } //关闭资源 fileOutputStream.close(); inputStream.close(); urlConnection.disconnect();//断开连接 } }
继续加油!!! ^ _ ^
这篇关于基础入门之网络编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求