网络编程
1.1 网络通信要素
通信地址
- ip(互联网协议地址,每一台主机分配一个逻辑地址)
- 端口号(每个应用程序对应一个端口号)
规则:网络协议
http,ftp(文件上传),smtp(发邮件)
网络编程的要素:
- ip和端口号:关于ip的类
- 网络通信协议:关于udp和tcp的类
1.2 IP
ip地址:用Java类InetAdderss表示
- 分类
- ipv4/ipv6
- iPv4:127.0.0.1
- ipv6:8个无符号整数。2001:0bb2:aaaa:0015:0000:0000:1aaa:1312
- 公网(互联网)-私网(局域网)
- ABCD类地址
- 192.168.xx.xx 内部组织使用
- ipv4/ipv6
InetAddress的使用
//查询本机ip
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress);
InetAddress inetAddress1 = InetAddress.getByName("localhost");
System.out.println(inetAddress1);
//查询网站ip地址
InetAddress google = InetAddress.getByName("www.google.com");
System.out.println(google);
System.out.println("---------");
System.out.println(google.getCanonicalHostName());//规范的名字
System.out.println(google.getHostAddress());//ip
System.out.println(google.getHostName());//域名
1.3 端口
端口表示计算机上的一个程序的进程
使用16bits端口号来表示和区别网络中的不同应用程序
-
不同的进程有不同的端口号
-
端口分类
-
公有端口 0-1023
- HTTP:80
- HTTPS:443
- FTP:21
- Telent:23
-
程序注册端口:1024-49151
- Tomcat:8080
- MySQL:3306
- Oracle:1521
-
动态,私有:49152~65535
InetAddress inetAddress=new InetSocketAddress("127.0.0.1",8080)
-
1.4 通信协议
协议相当于约定
TCP/IP协议簇:一组协议
- TCP:用户传输协议
- UDP:用户数据报协议
- IP:网络互连协议
TCP三次握手,四次挥手记忆
- 文件流读取流程
客户端
1.获取服务端的地址,端口号
2.创建一个socket
3.将数据写入os
public class TcpClientDemo01 {
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();
}
}
}
}
服务端
1.建立服务端口,serverSocket
2.接受客户端的socket,accept
3.将客户端数据读到is
4.is读入buffer中,并从buffer写入到baos
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream baos=null;
try {
//1.服务端有一个地址
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) {
e.printStackTrace();
}
}
if (is!=null){
try {
is.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();
}
}
}
}
}
文件上传
客户端
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
//1.创建一个socket连接
Socket socket = new Socket("127.0.0.1", 9000);
//2.创建一个输出流
OutputStream os = socket.getOutputStream();
//3.读取文件
FileInputStream fis = new FileInputStream(new File("2.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();
//服务端string.getByte()方法返回的是byte数组,用byte数组的输出流来接受服务端getbytes的结果
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len1;
byte[] buffer1 = new byte[1024];
while ((len1=inputStream.read(buffer1))!=-1){
baos.write(buffer1,0,len1);
}
System.out.println(baos.toString());
//5.关闭资源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
服务端
public class TcpServerDemo02 {
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("receive.jpg"));
int len;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//通知客户端,服务端已经接受完毕
OutputStream os = socket.getOutputStream();
os.write("服务端已经接受完毕,客户端(你)可以断开".getBytes());
//关闭资源
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
Tomcat
服务器:
- 自定义
- Tomcat
客户端:
- 自定义:C (C/S架构)
- 浏览器:B (B/S架构)
同一个协议下端口号不能被占用,tomcat和代码使用同一个端口,另一个服务就启动报错
1.5 UDP
不需要连接,不需要知道对方地址
发送端
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
//1.建立一个socket
DatagramSocket socket = new DatagramSocket();
//2.建包
String msg="hello,server";
InetAddress localhost = InetAddress.getByName("localhost");
int port=9090;
//包=数据,起始位置,终止位置,发送到的ip地址和端口号
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length,localhost,port);
//3.发送包
socket.send(packet);
//4.关闭流
socket.close();
}
}
接收端
public class UdpServerDemo01 {
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 java.lang.String(packet.getData(),0,packet.getLength()));
//关闭连接
socket.close();
}
}
聊天实现
发送方
public class UdpSender {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
//准备数据:
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){
//接收packet
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
//断开连接 bye
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
string和byte[]的切换
//byte[]切换为为string
byte[] data=new byte[1024];
String datas=new String(data,0,data.length);
//string切换为byte[]
String str="hello";
byte[] s=str.getBytes();
多线程实现聊天
发送端
public class TalkSend implements Runnable{
DatagramSocket socket =null;//将该类的公有属性提取
BufferedReader reader =null;
private int fromPort;//对端口,ip,目地端口提取属性
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {//构造器,对端口和ip赋值,,并初始化socket和reader
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket=new DatagramSocket(fromPort);
reader=new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {//将操作内容写在run中
while (true){
try {
String data= reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(toIP,toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
接收端
public class TalkReceive implements Runnable{
private int port;
DatagramSocket socket =null;
private String msgFrom;
public TalkReceive(int port,String msgFrom) {
this.port = port;
this.msgFrom=msgFrom;
try {
socket=new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
//接收packet
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
//断开连接 bye
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom+": "+receiveData);
if (receiveData.equals("bye")){
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
两个类互相发送信息,分别有发送和接受线程,端口号对应
teacher
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(1234,"localhost",443)).start();
new Thread(new TalkReceive(2222,"student")).start();
}
}
student
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(9090,"localhost",2222)).start();
new Thread(new TalkReceive(443,"teacher")).start();
}
}
1.6 URL
统一资源定位符
格式:
协议://ip地址:端口/项目名/资源
URL下载网络资源
public class urlDemo {
public static void main(String[] args) throws IOException {
//1.资源下载地址
URL url = new URL("https://m7.music.126.net/20200527212021/538aad8fb4376a904efb50b6bdda1fb4/ymusic/fec0/d906/6af2/434cbfde0938735887b928a3e117517e.mp3");
//2.连接到这个资源 http
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("自救.mp3");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,buffer.length);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}