1.网络通信的要素
如何实现网络的通信
通信双方地址
规则:网络通信协议
TCP/IP参考模型:
1.网络编程中有一个准确的问题
-
如何准确定位到网络上的一台或多台主机 -
找到主机之后如何通讯
2.网络编程中的要素
P地址
ip地址:InteAddress
唯一定位一台网络计算机(身份证一样)
127.0.0.1 :本机地址
ip的分类
IPV4/IPV6
-
IPV4 :127.0.0.1 ,由四个字节组成,0~255,共42亿个,2011年已用尽 -
IPV6 : 128位,8个无符号整数
公网(互联网) - 私网(局域网)
import java.net.InetAddress;
import java.net.UnknownHostException;
//测试IP
public class TestAddress {
public static void main(String[] args) {
try {
/*查询本机地址*/
InetAddress address1= InetAddress.getByName("127.0.0.1");
System.out.println("address1 :" + address1);
InetAddress address3= InetAddress.getByName("127.0.0.1");
System.out.println("address3 :" + address3);
InetAddress address4 = InetAddress.getLocalHost();
System.out.println("address4 :" + address4);
// 查询网站ip
InetAddress address2= InetAddress.getByName("www.baidu.com");
System.out.println("address2 :" + address2); //www.baidu.com/14.215.177.38
// 常用方法
System.out.println("address2 :" + address2.getAddress()); //[B@28d93b30
System.out.println("address2 :" + address2.getCanonicalHostName()); //www.baidu.com //规范名
System.out.println("address2 :" + address2.getHostAddress()); //14.215.177.38 ip
System.out.println("address2 :" + address2.getHostName()); //www.baidu.com 域名/自己电脑名
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
端口
端口表示计算机上的一个程序的进程
netstat -aon 查看所有端口 netstat -ano|findstr "8080" ?查看指定端口 tasklist|findstr "8080" 查看指定端口的进程
import java.net.InetSocketAddress;
?
public class TestIntSocketaAddress {
? public static void main(String[] args) {
? ? ? InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
? ? ? InetSocketAddress socketAddress1 = new InetSocketAddress("localhiost", 8080);
? ? ? System.out.println(socketAddress);
? ? ? System.out.println(socketAddress1);
?
? ? ? System.out.println(socketAddress.getAddress());
? ? ? System.out.println(socketAddress.getHostName());
? ? ? System.out.println(socketAddress.getPort());
? }
}
?
通讯协议
协议:相当于是一种约定,就好比大家都说普通话
TCP/UDP协议簇 :实际上是一种协议
-
TCp:用户传输协议 -
UDP:用户数据报协议 -
IP:网络互联协议
TCP UDP对比
TCP: 相当于打电话
-
连接稳定 -
三次握手,四次挥手 -
最少需要三次,才能保证稳定链接 A:你愁啥 B:瞅你咋地 A:打一架
-
客户端/服务端 -
传输完成,释放连接,效率低
UDP:相当于发短信
-
不连接,不稳定 -
客户端,服务端:没有明确的界限 -
不管对面有没有准备好,都可以发给你 -
DDOS : 洪水攻击(饱和攻击)
TCP
客户端:
-
连接服务器 Socket -
发送消息
package lesson2;
?
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
?
/*客户端*/
public class TcpClintDemo1 {
? public static void main(String[] args) {
? ? ? Socket socket = null;
? ? ? OutputStream outputStream = null;
? ? ? try {
? ? ? ? ? //1.服务器地址
? ? ? ? ? InetAddress serverIP = InetAddress.getByName("127.0.0.1");
? ? ? ? ? int port = 9999;
// ? ? ? ? ? ?2.创建一个socket连接
? ? ? ? ? socket = new Socket(serverIP, port);
// ? ? ? ? ? ?3.发送消息IO流
? ? ? ? ? outputStream = socket.getOutputStream();
? ? ? ? ? outputStream.write("你好".getBytes());
? ? ? } catch (UnknownHostException e) {
? ? ? ? ? e.printStackTrace();
? ? ? } catch (IOException 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();
? ? ? ? ? ? ? }
? ? ? ? ? }
? ? ? }
? }
}
服务器
-
建立服务的端口ServerSocker -
等待用户的连接 accept -
接收用户消息
package lesson2;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class TcpSercverDemo2 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
// 1.地址
serverSocket = new ServerSocket(9999);
while (true) {
// 2.等待地址连接
socket = serverSocket.accept();
//3.读取客户端消息
inputStream = socket.getInputStream();
// 4.管道流
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 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 (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
文件上传
服务器端
package lesson2;
?
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
?
//服务端 --接收文件
public class TcpSercverDemo2 {
? public static void main(String[] args) throws Exception{
// ? ? ? ?1.创建服务
? ? ? ServerSocket serverSocket = new ServerSocket(9000);
// ? ? ? ?2.监听客户端连接
? ? ? Socket socket = serverSocket.accept();//阻塞式连接,会一直等待客户端连接
// ? ? ? ?3.获取输入流
? ? ? InputStream is = socket.getInputStream();
// ? ? ? ?4.文件输出
? ? ? FileOutputStream fos = new FileOutputStream(new File("123.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 lesson2;
?
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
?
/*客户端*/
public class TcpClintDemo2 {
? public static void main(String[] args) throws Exception {
// ? ? ? ?1.创建socker连接
? ? ? Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
// ? ? ? ?2.创建文件输出流
? ? ? OutputStream os = socket.getOutputStream();
// ? ? ? ?3.文件流
? ? ? FileInputStream fis = new FileInputStream(new File("123.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 byteArrayOutputStream = new ByteArrayOutputStream();
? ? ? byte[] buffer2 = new byte[2014];
? ? ? int len2;
? ? ? ?while ((len2 = inputStream.read(buffer2)) != -1) {
? ? ? ? ? byteArrayOutputStream.write(buffer2, 0, len2);
? ? ? }
?
? ? ? System.out.println(byteArrayOutputStream.toString());
?
// ? ? ? ?5.关闭异常
? ? ? byteArrayOutputStream.close();
? ? ? inputStream.close();
? ? ? fis.close();
? ? ? os.close();
? ? ? socket.close();
? }
}
?
UDP:消息发送
想发短信:不用连接,需要知道对方地址
发送消息
package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//UDP不需要连接服务器
public class UdpClientDemo1 {
public static void main(String[] args) throws Exception {
// 1.创建一个socket
DatagramSocket socket = new DatagramSocket();
// 2.建立一个包
String msg = "你好啊";
// 3.发送给谁
InetAddress localhoost = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhoost, port);
// 4.发送包
socket.send(packet);
// 5.关闭流
socket.close();
}
}
接收端
package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
///等待客户端连接
public class UdpServerDemo1 {
public static void main(String[] args) throws Exception {
// 开放端口
DatagramSocket socket = new DatagramSocket(9090);
// 接收包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet); //阻塞接收
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
// 关闭连接
socket.close();
}
}
UDP模拟聊天
循环发送消息
package Chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class UdpSenderDemo1 {
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("bey")) {
break;
}
}
socket.close();
}
}
循环接收消息
package Chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiveDemo1 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while (true) {
// 准备接收包裹
byte[] continer = new byte[1024];
DatagramPacket packet = new DatagramPacket(continer, 0, continer.length);
socket.receive(packet); //阻塞式接收包裹
// 断开连接
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
if (receiveData.equals("bey")) {
break;
}
}
socket.close();
}
}
在线咨询:两个人都可以发送,接收
接收端:
package Chat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String magFrom;
public TalkReceive(int port, String magFrom) {
this.port = port;
this.magFrom = magFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
// 准备接收包裹
byte[] continer = new byte[1024];
DatagramPacket packet = new DatagramPacket(continer, 0, continer.length);
socket.receive(packet); //阻塞式接收包裹
// 断开连接 bey
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(magFrom + " :" + receiveData);
if (receiveData.equals("bey")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
读取:
package 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;
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 ( Exception e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
String data = null;
try {
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("bey")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
创建老师线程
package Chat;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}
创建学生线程
package Chat;
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
URL下载网络资源
URL:统一资源定位符,定位互联网上的某个资源
DNS :域名解析 ,就是将www. baidu .com?解析为xx/xx/xx的ip
协议://IP地址:端口 / 项目名 / 资源
package Chat;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDemo {
public static void main(String[] args) throws Exception {
// 下载地址
URL url = new URL("http://m704.music.126.net/20220309120335/1326f5efd139f4adfdb527975fb4b460/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/8837130090/e64d/e6e0/76ad/4b9e06388e5bf007db0a99c0170a662c.m4a?authSecret=0000017f6cc1cf4104d30aaba034595c");
// 2.连接到资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("luck.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();// 断开连接
}
}
// 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()); //参数
|