TCP和UDP的区别https://blog.csdn.net/HBliucheng/article/details/114084836
一、TCP实现聊天以及文件上传下载
1,TCP实现信息发送与接收
客户端
/**
* TCP实现消息发送之客户端发送消息
*/
@Test
void tcpClient1() throws IOException {
// 首先要知道服务端额ip和端口
InetAddress serverIp = InetAddress.getByName("127.0.0.1");
int port=9999;
// 创建一个socket连接
Socket socket = new Socket(serverIp, port);
OutputStream os = socket.getOutputStream();
String message="你好 李焕英!";
os.write(message.getBytes());
}
服务端
/**
* TCP实现消息发送之服务端接收消息
*/
@Test
void tcpServer1() throws Exception{
// 自己创建一个地址
ServerSocket serverSocket = new ServerSocket(9999);
// 等待客户端连接过来
Socket socket = serverSocket.accept();
// 读取客户端消息
InputStream is = socket.getInputStream();
// 创建一个管道流用于接收消息
ByteArrayOutputStream 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());
}
测试结果
启动服务端再启动客户端
发现服务端接收到了
2,TCP实现文件发送
客户端
/**
* TCP实现文件上传之客户端发送文件
*/
@Test
public void tcpFileUploadCilent() throws IOException {
InetAddress serverIp = InetAddress.getByName("127.0.0.1");
int port=9000;
Socket socket = new Socket(serverIp, port);
// 创建一个输出流
OutputStream os = socket.getOutputStream();
// 读取文件
FileInputStream fis = new FileInputStream(new File("src\\main\\resources\\static\\client.jpg"));
// 写出文件,发送文件给服务端
byte[] buffer = new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
// 通知服务端我已经发送完成
socket.shutdownOutput();
// 确认服务端已经接收完成,才能断开连接
InputStream is = socket.getInputStream();
// 创建管道流接收服务端发送的消息信息
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while ((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
// 关闭流
baos.close();
is.close();
fis.close();
os.close();
socket.close();
}
服务端
/**
* TCP实现文件上传之服务端接收文件
*/
@Test
public void tcpFileUploadServer() throws IOException {
int port=9000;
// 创建一个socket通信服务
ServerSocket serverSocket = new ServerSocket(port);
// 监听客户端的连接,阻塞式监听,会一直等待客户端连接
Socket socket = serverSocket.accept();
// 获取输入流
InputStream is = socket.getInputStream();
// 创建一个文件输出流
FileOutputStream fos = new FileOutputStream(new File("src\\main\\resources\\static\\server.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
// 服务端接收完成后需要告知客户端我已经接收完成
String msg="我已经接收完成,请断开连接";
OutputStream os = socket.getOutputStream();
os.write(msg.getBytes());
// 关闭流
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
文件上传前
启动服务端再启动客户端
客户端运行结果
文件中多了server.jpg
3,多线程实现聊天
package com.udpTalk;
import lombok.AllArgsConstructor;
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;
/**
* 发送方
* @author LiuCheng
* @data 2021/2/24 17:05
*/
public class TalkSend implements Runnable {
/**
* 发送方port
*/
private int toPort;
/**
* 发送方ip
*/
private String toIp;
/**
*接收方ip
*/
private int fromPort;
private DatagramSocket socket;
private BufferedReader reader;
private static final String SHUTDOWM_MESSAGE="bye";
public TalkSend(int toPort, String toIp, int fromPort) {
this.toPort = toPort;
this.toIp = toIp;
this.fromPort = fromPort;
// 创建通信
try {
socket = new DatagramSocket(fromPort);
// 输入信息
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
String data = reader.readLine();
// 封装发送包
byte[] dataBytes = data.getBytes();
DatagramPacket packet = new DatagramPacket(dataBytes, 0, dataBytes.length, new InetSocketAddress(toIp, toPort));
socket.send(packet);
// 中断聊天
if(data.equalsIgnoreCase(SHUTDOWM_MESSAGE)){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
服务端
package com.udpTalk;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* 接收方
*
* @author LiuCheng
* @data 2021/2/24 17:24
*/
public class TalkReveive implements Runnable {
/**
* 接收方port
*/
private int port;
/**
* 接收方获取的信息
*/
private String msgFrom;
private DatagramSocket socket;
private static final String SHUTDOWM_MESSAGE="bye";
public TalkReveive(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[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
// 阻断式接收
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgFrom+":" +receiveData);
// 中断聊天
if(receiveData.equalsIgnoreCase(SHUTDOWM_MESSAGE)){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
聊天方,学生
package com.udpTalk;
/**
* 学生方
* @author LiuCheng
* @data 2021/2/25 9:39hj
*/
public class Student {
public static void main(String[] args) {
// 发送消息
new Thread(new TalkSend(9999,"127.0.0.1",5555)).start();
// 接收消息
new Thread(new TalkReveive(8888,"老师")).start();
}
}
聊天方,老师
package com.udpTalk;
/**
* 老师方
* @author LiuCheng
* @data 2021/2/25 9:43
*/
public class Teacher {
public static void main(String[] args) {
// 发送消息
new Thread(new TalkSend(8888,"127.0.0.1",6666)).start();
// 接收消息
new Thread(new TalkReveive(9999,"学生")).start();
}
}
启动学生和老师开启双方聊天,现在老师这边输入信息,然后再学生那边输入信息结果如下
二、UDP实现信息发送
1,UDP实现信息发送与接收
发送方
/**
* udp 发送消息方
* @throws IOException
*/
@Test
public void udpSendTest1() throws IOException {
// 不需要连接服务器,建立一个socket
DatagramSocket socket = new DatagramSocket();
// 创建需要发送的信息
InetAddress servetIp = InetAddress.getByName("127.0.0.1");
int port=9090;
// 封装需要发送的数据,发送给谁
String msg="你好,李焕英";
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, servetIp, port);
socket.send(datagramPacket);
// 关闭发送包
socket.close();
}
接收方
/**
* udp接收消息方
*/
@Test
public void udpReceiveTest1() throws IOException {
// 开放端口
int port=9090;
DatagramSocket socket = new DatagramSocket(port);
// 接收数据包
byte[] buffer = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);
// 阻塞接收
socket.receive(datagramPacket);
// 查看数据从哪里来的
System.out.println(datagramPacket.getAddress().getHostAddress());
// 查看接收到的数据
System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));
}
测试
先运行接收方,再运行发送方
2,UDP实现信息多次发送与接收
发送方
package com.udp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
* @author LiuCheng
* @data 2021/2/24 16:46
*/
public class UdpTalkSender {
public static void main(String[] args) throws IOException {
// 建立一个socket连接
String serverIp="127.0.0.1";
DatagramSocket socket = new DatagramSocket(9001);
// 获取控制台的信息来发送
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inputStreamReader);
while (true){
String data=reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(serverIp, 9002));
socket.send(packet);
// 输入bye时中断
if(data.equals("bye")){
break;
}
}
socket.close();
}
}
接收方
package com.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* @author LiuCheng
* @data 2021/2/24 16:46
*/
public class UdpTalkReseive {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9002);
while (true) {
// 准备接收包
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
// 阻塞式接收信息
socket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
// 断开连接 bye
if(receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
测试
三、URL下载网络资源
1,URL的常用API介绍
/**
* URLAPI
* @throws MalformedURLException
*/
@Test
public void test1() throws MalformedURLException {
URL url = new URL("https://localhost:8080/static/hello.html?user=a&password=123");
// 获取协议 https
System.out.println(url.getProtocol());
//获取全路径 /static/hello.html?user=a&password=123
System.out.println(url.getFile());
// 获取主机ip localhost
System.out.println(url.getHost());
// 获取端口 8080
System.out.println(url.getPort());
// 获取文件 /static/hello.html
System.out.println(url.getPath());
// 获取参数 user=a&password=123
System.out.println(url.getQuery());
}
2,URL下载网络资源
@Test
public void test2() throws IOException {
// 下载地址
String imgUrl="http://img.sccnn.com/bimg/340/02049.jpg";
URL url = new URL(imgUrl);
// 连接这个下载资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(30000);
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("src\\main\\resources\\static\\down.jpg");
byte[] bytes = new byte[1024];
int len;
while ((len=is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
测试
目录
运行后的目录