一、主要内容
1、网络编程中有两个主要问题
- 如何准确的定位到网络上的一台或者多台主机
- 找到主机之后如何进行通信
2、网络编程中的要素
- IP和端口号
- 网络通信协议 udp ,tcp
3、万物皆对象
二、IP
ip地址:InetAddress
- 唯一定位一台网络上计算机
- 127.0.0.1:本机localhost
- ip地址的分类
- ipv4/ipv5
- IPV4/ipv6
- IPV4 127.0.0.1 4个字节组合,0-255,42亿:30亿在北美,亚洲4亿
- IPV4/ipv6
- ipv4/ipv5
- 域名:记忆IP问题
package com.jjl.Network;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机
InetAddress inetAddress1=InetAddress.getByName("127.0.0.1");
InetAddress inetAddress3=InetAddress.getByName("localhost");
InetAddress inetAddress4=InetAddress.getLocalHost();
System.out.println(inetAddress1);
System.out.println(inetAddress3);
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());//规范名字(IP)
System.out.println(inetAddress2.getHostAddress());//ip
System.out.println(inetAddress2.getHostName());//域名
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
三、端口
端口表示计算机上的一个程序的进程:
-
不同的进程有不同的端口号,用来区分软件
-
被规定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~65535
dos命令
netstat -ano 查看所有的端口
netstat -ano|findstr “8080” 查看指定的端口
四、协议
1、TCP UDP对比
TCP:
- 连接,稳定
- 三次握手(建立连接) 四次挥手(断开连接)
- 客户端、服务端
- 传输完成,释放连接,效率底
UDP
- 不连接,不稳定
- 客户端、服务端:没有明确的界限
- 不管有没有准备好,都可以发给你
- 导弹
- DDOS:洪水攻击
2、TCP
2.1 建立通信发送消息
服务端
package com.jjl.Network;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream baos=null;
try {
//创建一个地址
serverSocket=new ServerSocket(9999);
//2、等待客户端连接
socket=serverSocket.accept();
//3、读取客户端的消息
is=socket.getInputStream();
//管道流
baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos!=null){
try {
baos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (is!=null){
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
客户端
package com.jjl.Network;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket=null;
OutputStream os=null;
//1.要知道服务器的地址,端口号
try {
InetAddress serverIP=InetAddress.getByName("127.0.0.1");
int port=9999;
//2、创建一个socket连接
socket=new Socket(serverIP,port);
//3.发信息IO流
os = socket.getOutputStream();
os.write("你好,欢迎学习Java".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (os!=null){
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
先启动服务端,再启动客户端
2.2 文件上传
服务器端
package com.jjl.Network;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws IOException {
//1.创建服务
ServerSocket serverSocket=new ServerSocket(9000);
//2.监听客户端的连接
Socket socket=serverSocket.accept();//堵塞式监听,会一直等待客户端连接
//3.获取输入流
InputStream is = socket.getInputStream();
//4.文件输出
FileOutputStream fos=new FileOutputStream(new File("E:\\study_file\\Java\\demo\\IOTest\\File.jpg"));
byte[] buffer=new byte[1024];
int len;
while ((len= is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//通知客户端我接受完毕
OutputStream os=socket.getOutputStream();
os.write("我接收完毕了,你可以断开了".getBytes());
//关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
客户端
package com.jjl.Network;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
//1.创建一个socket连接
Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2.创建一个输出流
OutputStream os = socket.getOutputStream();
//3.文件流
FileInputStream fis=new FileInputStream(new File("E:\\study_file\\Java\\demo\\IOTest\\test.jpg"));
//4.写出文件
byte[] buffer=new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
//通知服务器,我已经结束了
socket.shutdownOutput();//已经传输完了
//确定服务端接收完毕,才能断开连接
InputStream inputStream= socket.getInputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer2=new byte[2048];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//5.关闭资源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
五、Tomcat
服务端
- 自定义S
- Tomcat服务器 S :java开发
客户端
- 自定义C
- 浏览器B
六、UDP
1、发信息,不用建立连接
接收端
package com.jjl.Network;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//还是要等待客户端连接
public class UDPServerDemo01 {
public static void main(String[] args) throws Exception {
//1.开放端口
DatagramSocket socket=new DatagramSocket(9090);
//2.接收数据
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();
}
}
发送端
package com.jjl.Network;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClientDemo01 {
public static void main(String[] args) throws Exception {
//1.建立一个Socket
DatagramSocket socket = new DatagramSocket();
//2.建个包
String msg="你好啊,服务器!";
//发送给谁
InetAddress localhost= InetAddress.getByName("localhost");
int port=9090;
DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
//3.发送包
socket.send(packet);
//4.关闭流
socket.close();
}
}
2、单向循环发送消息
接收端
package com.jjl.Network.Chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiveDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while (true){
//准备接收包裹
byte[] container=new byte[2048];
DatagramPacket packet=new DatagramPacket(container,0,container.length);
socket.receive(packet);//阻塞式接收包裹
//byte[] data = packet.getData();
String receveData = new String(packet.getData(),0,packet.getLength());
System.out.println(receveData);
//断开连接 bye
if (receveData.equals("bye")){
break;
}
}
socket.close();
}
}
发送端
package com.jjl.Network.Chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UdpSenderDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket=new DatagramSocket(8080);
//准备数据,控制台读取System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String data=reader.readLine();
byte[] datas=data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
socket.send(packet);
if(data.equals("bye")){
break;
}
}
socket.close();
}
}
3、双向接收发送消息(多线程)
接受线程
package com.jjl.Network.Chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TallkRecevice implements Runnable{
DatagramSocket socket=null;
private int port;
private String msgfrom;
public TallkRecevice(int port,String msgfrom){
this.msgfrom=msgfrom;
this.port=port;
try {
socket=new DatagramSocket(port);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
//准备数据,控制台读取System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
try {
byte[] container=new byte[2048];
DatagramPacket packet=new DatagramPacket(container,0,container.length);
socket.receive(packet);//阻塞式接收包裹
String receveData = new String(packet.getData(),0,packet.getLength());
System.out.println(msgfrom+":"+receveData);
//断开连接 bye
if (receveData.equals("bye")){
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
socket.close();
}
}
发送线程
package com.jjl.Network.Chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable {
DatagramSocket socket=null;
BufferedReader reader=null;
private int fromport;
private String toIP;
private int toPort;
public TalkSend(int fromport, String toIP, int toPort) {
this.fromport = fromport;
this.toIP = toIP;
this.toPort = toPort;
try {
socket=new DatagramSocket(fromport);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
while (true) {
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));
socket.send(packet);
if (data.equals("bye")) {
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
角色1,同时启动接收和发送的线程
package com.jjl.Network.Chat;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TallkRecevice(9999,"学生")).start();
}
}
角色2,同时启动接收和发送的线程
package com.jjl.Network.Chat;
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TallkRecevice(8888,"老师")).start();
}
}
七、URL
https://www.baidu.com/
同一资源定位符:定位互联网上的某个资源
DNS域名解析:https://www.baidu.com/ ——>IP地址
下载网络上的资源(图片,文件,音视频)
package com.jjl.Network.URL;
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{
//1.下载地址
URL url =new URL("https://m801.music.126.net/20220613170619/7463b287d9a21198f428fb0e9e3e2b53/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/14957840870/437c/3da9/3026/9691b1df0d6973f5b0b65550940920d1.m4a");
//2.连接到这个资源
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
FileOutputStream fos=new FileOutputStream("揉碎的夜光.m4a");
byte[] buffer=new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len);//写入数据
}
fos.close();
inputStream.close();
urlConnection.disconnect();//断开连接
}
}