网络编程
网络通信的要素
如何实现网络的通信?
通信双方地址:
- ip
- 端口号
规则:网络通信的协议
Tcp/IP参考模型:
IP
ip地址的分类
- ipv4/ipv6
- IPV4 127.0.0.1 4个字节组成。 0~255。
- IPV6 128位,8个无符号整数!
- 公网(互联网)-私网(局域网)
ip地址:在java.net包下
在java代码中的引用:
public class TestInetAddress {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress inetAdress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAdress1);
InetAddress inetAdress3 = InetAddress.getByName("localhost");
System.out.println(inetAdress3);
InetAddress inetAdress4 = InetAddress.getLocalHost();
System.out.println(inetAdress4);
//查询网站ip地址
InetAddress inetAdress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAdress2);
//常用方法
System.out.println(inetAdress2.getAddress());//返回字节数组,一组地址
System.out.println(inetAdress2.getCanonicalHostName());//规范的名字
System.out.println(inetAdress2.getHostAddress());//ip
System.out.println(inetAdress2.getHostName());//域名,或者是自己电脑的名称
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
结果:
/127.0.0.1
localhost/127.0.0.1
PC-20170320CXDY/192.168.196.194
www.baidu.com/39.156.66.14
[B@12a3a380
39.156.66.14
39.156.66.14
www.baidu.com
端口
端口表示计算机上的一个程序的进程;
-
不同的进程有不同的端口!用来区分软件
-
被规定0~65536
-
TCP和UDP分别占有65535个,即电脑端口总数为65535*2。单个协议下,端口号不能冲突。
-
端口分类
- 公有端口 0~1023
- HTTP : 80
- HTTPS : 443
- FTP : 21
- Telent : 23
- 程序注册端口:1024~49151,分配用户或者程序
- Tomcat:8080
- MySQL:3306
- Oracle:1521
- 动态、私有:49152~65535
- 公有端口 0~1023
-
一些常用dos命令
netstat -ano //查看所有的端口 netstat -ano |findstr “端口号” //查看指定的端口号 |代表管道符,过滤 tasklist|findstr "端口号" //查看指定端口号的进程
代码:
package pers.mobian.socket;
import java.net.InetSocketAddress;
public class TestSocket02 {
public static void main(String[] args) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);
InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost",8080);
System.out.println(inetSocketAddress);
System.out.println(inetSocketAddress2);
System.out.println(inetSocketAddress.getAddress());//获取地址
System.out.println(inetSocketAddress.getHostName());//获取主机名字
System.out.println(inetSocketAddress.getPort());//获取端口
}
}
结果:
/127.0.0.1:8080
localhost/127.0.0.1:8080
/127.0.0.1
activate.navicat.com
8080
C:\Windows\System32\drivers\etc\hosts
可以配置本机映射地址
通信协议
网络通信协议:速率、传输码率、代码结构、传输控制…
TCP/IP协议簇:是一组协议
- TCP:用户传输协议
- UDP:用户数据报协议
- IP:网络互连协议
TCP:打电话
- 连接稳定
- 三次握手、四次挥手
- 客户端、服务器
- 传输完成、释放连接、效率低
UDP:发短信
- 不连接、不稳定
- 客户端、服务器:没有明确的界限
- 不管有没有准备好,都可以发送给你
- DDOS:洪水攻击(发送大量的信息,堵塞端口,饱和攻击)
TCP实现聊天
文字传输:
- 客户端:
- 连接服务器 (Socket)
- 发送消息
//客户端
public class TestClientSocket {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
//1、要知道服务器得地址、端口号
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("你好,世界!".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭资源,对关闭得资源进行一个判定,如果没有开启则不需要关闭
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 服务器:
- 建立服务器的端口号 ServerSocket
- 等待用户的链接 accept
- 接受用户的信息
//服务器端
public class TestServersSocket {
public static void main(String[] args) throws Exception {
//1、给自己新建一个端口号
ServerSocket serverSocket = new ServerSocket(9999);
//2、等待客户端进行连接
Socket socket = serverSocket.accept();
//3、读取客户端的消息
InputStream inputStream = socket.getInputStream();
//4、管道流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer))!= -1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
//5、关闭资源(后开先关)
baos.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
TCP实现文件上传
文件上传:
客户端:
//客户端
public class TestClientSocket2 {
public static void main(String[] args) throws Exception {
//1、创建一个Socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
//2、创建一个输出流
OutputStream os = socket.getOutputStream();
//3、读取文件
FileInputStream fis = new FileInputStream(new File("dj.jpg"));
//4、写出文件
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
//5、确定服务器接受完毕,才能断开连接
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//6、关闭资源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
服务器:
//服务器
public class TestServersSocket2 {
public static void main(String[] args) throws Exception {
//1、创建服务
ServerSocket serverSocket = new ServerSocket(9999);
//2、监听客户端得连接
Socket socket = serverSocket.accept();//阻塞式监听,会一直等待
//3、获取输入流
InputStream is = socket.getInputStream();
//4、文件输出
FileOutputStream fos = new FileOutputStream(new File("3.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
//5、通知客户端,我接受完毕了
OutputStream os = socket.getOutputStream();
os.write("我接受完了".getBytes());
//6、关闭资源
os.close();
fos.close();
is.close();
}
}
初始Tomcat
服务端:
- 自定义 S
- Tomcat服务器 S
客户端:
- 自定义 C
- 浏览器 B
本地启动tomcat日志输出乱码,如何修改:
windows默认是GBK。
UDP消息发送
UDP没有服务器和客户端得概念,只有发送端和接收端得概念
涉及两个包:java.net.DatagramPacket(发送包) java.net.DatagramSocket(接受包)
发送端:
//发送端
public class TestUdpClient {
public static void main(String[] args) throws Exception {
//1、建立一个Socket
DatagramSocket socket = new DatagramSocket();
//2、建包
String msg="hello,世界";
InetAddress localost = InetAddress.getByName("127.0.0.1");
int port=9090;
//参数得列表分别是:数据,数据长度始,数据长度终,地址,端口号
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localost, port);
//3、发送包
socket.send(packet);
//4、关闭资源
socket.close();
}
}
接收端:
//接收端
public class TestUdpServer {
public static void main(String[] args) throws Exception {
//1、设置开放端口
DatagramSocket socket = new DatagramSocket(9090);
//2、准备接受数据包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);//阻塞式接受包裹
System.out.println(packet.getAddress().getHostAddress());
//3、将需要打印得数据进行格式转换
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
结果:
127.0.0.1
hello,世界
UDP聊天实现
循环发送消息
//循环发送,控制台输入
public class UdpSender {
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[] 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();
}
}
//循环接收
public class UdpReceive {
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);
//控制台打印
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
//断开连接 bye
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
UDP多线程在线咨询
实例代码:
发送端线程:TalkSend
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);
//准备数据:控制台读取system.in
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@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) {
e.printStackTrace();
}
}
socket.close();
}
}
接收端线程:TalkRecevice
public class TalkRecevice implements Runnable{
DatagramSocket socket =null;
private int port;
private String msgFrom;
public TalkRecevice(int port,String msgFrom) {
this.msgFrom=msgFrom;
this.port = port;
try {
socket=new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
//准备接受包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
//控制台打印
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom+":"+receiveData);
//断开连接 bye
if (receiveData.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
学生端:
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkRecevice(8888,"老师")).start();
}
}
老师端:
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkRecevice(9999,"学生")).start();
}
}
结果:
学生端:
老师好
老师:你好 今天可以答辩吗?
老师:可以
老师端:
学生:老师好 你好
学生:今天可以答辩吗? 可以
URL
https://www.baidu.com/
统一资源定位符:定位资源的,定位互联网上的某一个资源
DNS 域名解析 www.baidu.com xxx.x.x.x(ip)
协议://IP地址:端口/项目名/资源
测试代码:
public class URLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/helloWorld/index.jsp?username=axin&password=123");
System.out.println(url.getProtocol());//使用的协议
System.out.println(url.getHost());//主机IP
System.out.println(url.getPort());//使用的端口号
System.out.println(url.getPath());//文件路径
System.out.println(url.getFile());//文件的全路径
System.out.println(url.getQuery());//参数列表
}
}
从网络上获取资源:
public class UrlDown {
public static void main(String[] args) throws Exception {
//下载地址
URL url = new URL("https://m701.music.126.net/20210530211838/0f81f78bdf351532ef23f011261814dc/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/9043355488/0d7a/f21a/0634/d1591d80765af5ec04740ff0d12a63df.m4a");
//2.连接到这个资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("y.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();//断开连接
}
}