网络编程
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, 用完了。IPV6地址:fe80::915d:470e:d522:4339%16 ,128位。8个无符号整数
公网(互联网使用)–私网(局域网使用)
ABCD类地址192.168.xxx.xxx 就是专门给组织内部使用的,是局域网。
域名:记忆IP问题
IP:
import .InetAddress;import .UnknownHostException;//测试IPpublic 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("");System.out.println(inetAddress2);//常用的方法System.out.println(inetAddress2.getAddress());System.out.println(inetAddress2.getCanonicalHostName());//规范的名称System.out.println(inetAddress2.getHostAddress());//ipSystem.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:21Telent:23
程序注册端口: 1024-49151 ,分配用户或者程序
Tomcat:8080MySQL:3306Oracle:1521
动态、私有:49152-66535
netstat -ano #查看所有端口netstat -ano|findstr "5900" #查看指定端口tasklist|findstr "8696" #查看指定端口的进程ctrl+shift+esc #快捷键打开用户管理器
import .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 .InetAddress;import .Socket;import .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 .ServerSocket;import .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 .InetAddress;import .Socket;import .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 .ServerSocket;import .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 .DatagramPacket;import .DatagramSocket;import .InetAddress;import .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 .DatagramPacket;import .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 .DatagramPacket;import .DatagramSocket;import .InetSocketAddress;import .SocketException;public class UdpSenderDemo01 {public static void main(String[] args) throws Exception {DatagramSocket socket = new DatagramSocket(8888);//准备数据 控制台读取 System.inBufferedReader 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 .DatagramPacket;import .DatagramSocket;import .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);//阻塞式接收包裹//断开连接 结束语:bbbyte[] 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域名解析: xxx.x…x…x
格式===> 协议://ip地址:端口号/项目名/资源
import java.io.FileOutputStream;import java.io.InputStream;import .HttpURLConnection;import .URL;public class UrlDown {public static void main(String[] args) throws Exception {//下载地址URL url = new URL("https://m701./0616182423/f21fe1179214b3d27f2b0ea638317388/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/9313927104/a809/a937/4553/134c850ec96faf0314c72b2680a96683.m4a");//连接这个资源 httpHttpURLConnection 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();//断开连接}}
继续加油!!!^ _ ^
如果觉得《基础入门之网络编程》对你有帮助,请点赞、收藏,并留下你的观点哦!