2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
网络通信协议:通信协议是对计算机必须遵守的规则,只有遵守这些规则,计算机之间才能进行通信。
java.net 包中提供了两种常见的网络协议的支持
Three-way handshake in TCP: In the TCP protocol, during the preparation phase for sending data, there are three interactions between the client and the server to ensure a reliable connection.
协议 + IP地址 + 端口号
TCP通信能实现两台计算机之间的数据交互,通信的两端,要严格区分为客户端(Client)与服务端(Server)。
In Java, two classes are provided for implementing TCP communication programs:
Socket 类:该类实现客户端套接字,套接字指的是两台设备之间通讯的端点。
Construction method:
public Socket(String host, int port)
: Creates a socket object and connects it to the specified port number on the specified host. If the specified host is null, it is equivalent to specifying the loopback address (Loopback Address (127.xxx) is the local loopback address.)。
Member methods:
public InputStream getInputStream()
: Returns the input stream for this socket.public OutputStream getOutputStream()
: Returns the output stream of this socket.public void close()
: Close this socket.public void shutdownOutput()
: Disables the output stream for this socket.ServerSocket 类:这个类实现了服务器套接字,该对象等待通过网络的请求。
Construction method:
public ServerSocket(int port): Use this constructor to create a ServerSocket object and bind it to a specified port.
The parameter port is the port number.
Member methods:
public Socket accept()
: Listen and accept connections, and return a new Socket object for communicating with the client.
Will block until a connection is established.
TCP communication analysis:
Code example:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTCP {
public static void main(String[] args) throws IOException {
System.out.println("服务端启动 , 等待连接 .... ");
// 1.创建 ServerSocket对象,绑定端口,开始等待连接
ServerSocket ss = new ServerSocket(6666);
// 2.接收连接 accept 方法, 返回 socket 对象.
Socket server = ss.accept();
// 3.通过socket 获取输入流
InputStream is = server.getInputStream();
// 4.一次性读取数据
// 4.1 创建字节数组
byte[] b = new byte[1024];
// 4.2 据读取到字节数组中.
int len = is.read(b);
// 4.3 解析数组,打印字符串信息
String msg = new String(b, 0, len);
System.out.println(msg);
//5.关闭资源.
is.close();
server.close();
}
}
The server specifies the port number, obtains the Socket object through the accept() method, obtains the input stream through the client object, and finally reads the data and waits for the message sent by the client.
import java.net.Socket;
public class ClientTCP {
public static void main(String[] args) throws Exception {
System.out.println("客户端 发送数据");
// 1.创建 Socket ( ip , port ) , 确定连接到哪里.
Socket client = new Socket("localhost", 6666);
// 2.获取流对象 . 输出流
OutputStream os = client.getOutputStream();
// 3.写出数据.
os.write("你好么? tcp ,我来了".getBytes());
// 4. 关闭资源 .
os.close();
client.close();
}
}
When the client is created, the IP address and port number of the connection are specified to facilitate connecting to the server, obtaining the output stream and outputting data through the client Socket object.
数据准备:
Place a file named test.jpg under drive D and create a folder called test
Code example:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileUpload_Server {
public static void main(String[] args) throws IOException {
System.out.println("服务器 启动..... ");
// 1. 创建服务端ServerSocket
ServerSocket serverSocket = new ServerSocket(6666);
// 2. 循环接收,建立连接
while (true) {
Socket accept = serverSocket.accept();
/* 3. socket对象交给子线程处理,进行读写操作Runnable接口中,只有一个run方法,使用lambda表达式简化格式 */
new Thread(() -> {
try ( //3.1 获取输入流对象
BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
//3.2 创建输出流对象, 保存到本地 .
FileOutputStream fis = new FileOutputStream("D:/test/" + System.currentTimeMillis() + ".jpg");
BufferedOutputStream bos = new BufferedOutputStream(fis)) {
// 3.3 读写数据
byte[] b = new byte[1024 * 8];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
// 4.=======信息回写===========================
System.out.println("back ........");
OutputStream out = accept.getOutputStream();
out.write("上传成功".getBytes());
out.close();
//5. 关闭 资源
bos.close();
bis.close();
accept.close();
System.out.println("文件上传已保存");
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
Here, a server object is first created, and while(true) is used to ensure the continuous connection to the server. Then, a thread is started to ensure that when one user uploads a large file, the efficiency of uploading files by other users will not be affected. The file name is set using the system milliseconds + '.jpg' to ensure that the same file name will not be overwritten during upload.
import java.io.*;
import java.net.Socket;
public class FileUpload_Client {
public static void main(String[] args) throws IOException {
// 1.创建流对象
// 1.1 创建输入流,读取本地文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\test.jpg"));
// 1.2 创建输出流,写到服务端
Socket socket = new Socket("localhost", 6666);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
//2.写出数据.
byte[] b = new byte[1024 * 8 ];
int len ;
while (( len = bis.read(b))!=-1) {
bos.write(b, 0, len);
}
// 关闭输出流,通知服务端,写出数据完毕
socket.shutdownOutput();
System.out.println("文件发送完毕");
// 3. =====解析回写============
InputStream in = socket.getInputStream();
byte[] back = new byte[20];
in.read(back);
System.out.println(new String(back));
in.close();
// ============================
// 4.释放资源
socket.close();
bis.close();
}
}
Here we can see that our server successfully saved the file sent by the user to the hard disk.
Java enthusiasts are welcome to read the article. The author will continue to update it. I look forward to your attention and collection. . .