An overview
1. Network model
OSI( The Open System Interconnection (Open System Interconnection) model is a summary of the network system structure. The network is divided into seven layers: application layer, presentation layer, session layer, transport layer, network layer, and data link. layer, physical layer.
2. IP protocolThe network layer protocol specifies the rules for identifying and finding computers on the Internet.
3.TCP protocol
A data transmission protocol at the transport layer. The connection is established through a "three-way handshake" before data transmission, and then Sending data is suitable for
situations that require high data accuracy. Since a connection needs to be established before data transmission, the transmission speed is slow.
4.UDP protocolA data transmission protocol at the transport layer. There is no need to establish a connection before data transmission. It is suitable for accurate data processing. When the sexual requirements are not high, the data transmission is faster. Generally, chat information is transmitted through this protocol.
5. HTTP protocol
The HTTP protocol is an application layer protocol that provides an interface for the operating system or network applications to access network services.
6. Port port
When the data reaches the computer, in order to find the target application, an integer value is assigned to each application. , with a value of 0-65535, this integer value is the
port. It can be seen that the port represents an application program on the computer, ensuring that the data reaches the predetermined program accurately. A port cannot be occupied by multipleapplications at the same time. After an application ends, the port will not be released immediately. There is a memory delay occupation time, which is generally very short. Ports 0-1023 are already occupied by system applications and other applications. Avoid using ports in this range during program design. 7. Socket Socket
Socket is a tool for sending and receiving data. The sender sends data through the socket, and the receiver listens to the specified port through the socket to obtain data.
8. Regardless of whether TCP protocol or UDP protocol is used, data can only be sent in byte form.
2 TCP Programming
1. Closing the input stream or output stream obtained through the Socket will close the Socket.
2. The output stream obtained through the Socket must be closed after the output is completed, otherwise the corresponding input stream at the other end will be blocked. Since when closing the output stream through the output stream object,
closing the Socket object at the same time, the other end will be unable to obtain the object corresponding to the Socket, so theoutput stream can only be closed through the shutdownOutput method under the Socket. . 3. General steps for the client:
Socket socket=new Socket(String host,int port);//创建客户端Socket,发送与接收数据,需要指明服务器IP与端口OutputStream os=socket.getOutputStream();//获取输出流,向服务器发送数据..........
os.flush();
socket.shutdownOutput();//关闭输出流,防止服务器端阻塞InputStream is=socket.getInputStream();//获取输入流,输入流包含服务器的反馈信息............
socket.close();//关闭socket,同时关闭输入与输出流
4. General steps for the server:
ServerSocket server=new ServerSocket(int port);//建立服务器端套接字,指定监听端口Socket socket=server.accept();//获取访问客户端的Socket,阻塞线程InputStream is=socket.getInputStream();//获取输入流,其中包含客户端发送的数据.............
OutputStream os=socket.getOutputStream();//获取输出流,向客户端反馈信息..............
os.flush();
os.shutdownOutput();
server.close();
5.Demo
Client
package com.javase.networkCommunication.tcp.demo02;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class ImgClient {public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("192.168.146.1", 10007);
FileInputStream is = new FileInputStream("Files/1.jpg");
OutputStream os = socket.getOutputStream();byte[] buf = new byte[1024];// 先将数据读取到缓冲区,比频繁的从硬盘读取速度快int length = 0;while ((length = is.read(buf)) != -1) {
os.write(buf, 0, length);
}
os.flush();
socket.shutdownOutput();// 如果输出流不关闭,服务端对应的输入流会阻塞InputStream replyIs = socket.getInputStream();//不会阻塞线程byte[] buf01 = new byte[1024];int length01 = replyIs.read(buf01);
String reply = new String(buf01, 0, length01);
System.out.println(reply);
is.close();
socket.close();
}
}
Server
package com.javase.networkCommunication.tcp.demo02;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import org.junit.Test;public class ImgServer {
@Testpublic void test01() throws IOException {
ServerSocket serverSocket = new ServerSocket(10007);
Socket socket = serverSocket.accept();// 线程阻塞,等待请求System.out.println("hostAddress=" + socket.getInetAddress().getHostAddress());
InputStream is = socket.getInputStream();
FileOutputStream os = new FileOutputStream("Files/2.jpg");
System.out.println(1);byte[] buf = new byte[1024];int length = 0;
System.out.println(2);int count = 3;while ((length = is.read(buf)) != -1) {
os.write(buf, 0, length);
System.out.println(count++);
}
os.flush();
os.close();
System.out.println("图片上传结束");/*PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("success");*/OutputStream out = socket.getOutputStream();
out.write("success".getBytes());
out.flush();
socket.shutdownOutput();
System.out.println("响应数据已发出");
serverSocket.close();
}
}
Three UDP Programming
1. Data processing method
UDP protocol sends data in the form of packets, with a maximum value of 64k per packet.
2. General steps for sending data:
DatagramSocket socket=new DatagramSocket();//创建数据报套接字用于发送数据//DUP协议采用数据包分段发送数据,因此需要建立数据包,在数据包中指明目的地IP与端口DatagramPacket packet= DatagramPacket(byte buf[], int offset, int length,InetAddress address, int port);
socket.send(packet);
3. General steps for receiving data:
DatagramSocket socket=new DatagramSocket(int port);//创建监听指定端口的数据报套接字DatagramPacket packet=new DatagramPacket(byte buf[], int length);
socket.receive(packet);
The above is the detailed content of Detailed explanation of examples of network communication. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.