网络编程
目的:数据交换、通信
1. 网络通信的要素
- 通信双方地址(IP+端口号)
- 网络通信协议
Java万物皆对象
2. IP地址
IP地址的类:InetAddress
- 唯一定位一台网络上的计算机
- 127.0.0.1 本机地址
package com.xiaozhang.lesson01;
import java.net.InetAddress;
//InetAddress类,无构造器,使用静态方法
import java.net.UnknownHostException;
//测试IP
public class TestInetAdress {
public static void main(String[] args) {
try {
//查询本机地址
InetAddress inetAdress1 = InetAddress.getByName("127.0.0.1");
InetAddress inetAdress2 = InetAddress.getByName("localhost");
InetAddress inetAdress3 = InetAddress.getLocalHost();
//根据网站域名查询网站IP地址
InetAddress inetAdress4 = InetAddress.getByName("www.baidu.com");
//常用方法
System.out.println(inetAdress4.getCanonicalHostName());//规范ip
System.out.println(inetAdress4.getHostAddress());//ip
System.out.println(inetAdress4.getHostName());//域名
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
3. 端口
端口的类:InetScoketAddress
- 端口对应进程
- TCP / UDP下各0~65535
- 公有端口:0~1023
- 程序注册端口:1024~49151
- 动态、私有:49152~65535
//查询所有的端口
netstat -ano
//查询具体的端口
netstat -ano|findstr "8080"
//查询指定端口的进程
tasklist|findstr "8080"
package com.xiaozhang.lesson01;
import java.net.InetSocketAddress;
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);
System.out.println(inetSocketAddress.toString());
System.out.println(inetSocketAddress.getAddress());
System.out.println(inetSocketAddress.getHostName());
System.out.println(inetSocketAddress.getPort());
}
}
4. 网络通信协议
TCP/IP协议簇:实际上是一组协议
- TCP:用户传输协议
- UDP:用户数据报协议
- IP:网络互联协议
5. TCP
客户端
- 连接服务器Socket
- 发送消息
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端
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();
}
}
}
}
}
服务器
- 建立服务的端口ServerSocket
- 等待用户的连接 accept
- 接受用户的消息
package com.xiaozhang.lesson02;
import jdk.nashorn.internal.objects.annotations.Where;
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 {
//1.创建服务器地址
serverSocket = new ServerSocket(9999);
while (true){
//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 {
try {
/*
严谨写法:
if(baos!=null){
baos.close();
}
......
*/
//关闭资源
baos.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.1 文件上传
客户端
package com.xiaozhang.lesson02;
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("1111.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[1024];
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();
}
}
服务器
package com.xiaozhang.lesson02;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
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("receive1.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();
}
}
6. UDP
6.1 发送消息
发送端
package com.xiaozhang.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//UDP无连接
//发送端
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
socket.close();
}
}
接收端
package com.xiaozhang.lesson03;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//接收端
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(new String(packet.getData(),0,packet.getLength()));
//关闭socket
socket.close();
}
}
6.2 单向聊天
发送端
package com.xiaozhang.chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UdpSenderDemo01 {
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();
}
}
接收端
package com.xiaozhang.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[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);
if (receivedata.equals("bye")){
break;
}
}
socket.close();
}
}
6.3 双向聊天
学生,老师
工具类
package com.xiaozhang.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);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception 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();
}
}
package com.xiaozhang.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 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 {
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);
if (receivedata.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
7. URL
7.1 URL下载
package com.xiaozhang.lesson03;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDown {
public static void main(String[] args) throws Exception {
//下载地址
URL url = new URL("https://m801.music.126.net/20221214224441/ec1f536fb497eb2f6099a70434c1e5fd/jdyyaac/5252/0e5a/5153/e8095592ba909dd03ca4f9b6b8889840.m4a");
//连接到资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("download.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();
}
}