Detailed explanation of examples of network communication
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,同时关闭输入与输出流
Copy after login
4. General steps for the server:
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,同时关闭输入与输出流
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();
Copy after login
5.Demo
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();
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();
}
}
Copy after login
Server
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(); } }
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();
}
}
Copy after login
Three UDP Programming
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(); } }
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);
Copy after login
3. General steps for receiving data: DatagramSocket socket=new DatagramSocket();//创建数据报套接字用于发送数据//DUP协议采用数据包分段发送数据,因此需要建立数据包,在数据包中指明目的地IP与端口DatagramPacket packet= DatagramPacket(byte buf[], int offset, int length,InetAddress address, int port); socket.send(packet);
DatagramSocket socket=new DatagramSocket(int port);//创建监听指定端口的数据报套接字DatagramPacket packet=new DatagramPacket(byte buf[], int length);
socket.receive(packet);
Copy after login
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



How to optimize network communication in C++ big data development? Introduction: In today's big data era, network communication plays a vital role in data processing. For developers who use C++ for big data development, optimizing the performance of network communication is the key to improving data processing efficiency. This article will introduce some methods to optimize network communication in C++ big data development, with code examples. 1. Use high-performance network library In C++ big data development, choosing a high-performance network library is the first step to optimize network communication performance. These libraries are usually

Overview of how to achieve network time synchronization communication through PHP and NTP protocols: Network Time Protocol (Network Time Protocol, referred to as NTP) is a protocol used to synchronize computer system time. In network applications, accurate time synchronization is very important to ensure the normal operation of network services. In PHP, network time synchronization can be achieved by communicating with the NTP protocol. This article will introduce how to use PHP code to communicate with an NTP server to obtain accurate network time. step

How to solve: Java network communication error: connection timeout When communicating with Java network, you often encounter a connection timeout error. Connection timeout means that when establishing a network connection, the handshake process between the client and the server takes longer than the preset time limit. In network communication, connection timeout errors may be caused by multiple factors, such as network delay, slow server response, etc. This article will describe how to resolve connection timeout errors in Java network communications and provide some sample code. Check the network connection First we need to

Utilizing Swoole development functions to achieve high-concurrency network communication Summary: Swoole is a high-performance network communication framework based on the PHP language. It has features such as coroutines, asynchronous IO, and multi-process, and is suitable for developing highly concurrent network applications. This article will introduce how to use Swoole to develop high-concurrency network communication functions and give some code examples. Introduction With the rapid development of the Internet, the requirements for network communication are becoming higher and higher, especially in high-concurrency scenarios. Traditional PHP development faces weak concurrent processing capabilities

How to deal with network communication issues in C# requires specific code examples. Network communication is a very important technology in modern programming. Whether we are developing network applications, online games or remote data interaction, we all need to understand how to handle network communication issues in C#. This article will introduce some common ways to handle network communication in C# and provide corresponding code examples. TCP/IP Sockets TCP/IP Sockets is a reliable, connection-oriented network communication protocol. In C# we can use System.

The role of subnet mask and its impact on network communication efficiency Introduction: With the popularity of the Internet, network communication has become an indispensable part of modern society. At the same time, the efficiency of network communication has also become one of the focuses of people's attention. In the process of building and managing a network, subnet mask is an important and basic configuration option, which plays a key role in network communication. This article will introduce the role of subnet mask and its impact on network communication efficiency. 1. Definition and function of subnet mask Subnet mask (subnetmask)

How to solve: Java network communication error: Failed to parse URL When communicating over Java networks, you often encounter errors that fail to parse URL. This error usually occurs when parsing the URL, and the valid URL format cannot be correctly parsed. Before solving this problem, we need to understand some basic URL concepts and related tool classes provided by Java. URL is the abbreviation of Uniform Resource Locator, which is used to identify the location of resources on the network. A URL usually consists of protocol, host name, port number, path and query

How to use coroutines to achieve efficient network communication in GO language Introduction: With the rapid development of the Internet, network communication has become more and more important. In modern development, Go language is a concurrent programming language, and its powerful coroutine capabilities make network communication more efficient. This article aims to introduce how to use coroutines to achieve efficient network communication in Go language, including common server and client programming. 1. Basic concepts Before discussing how to use coroutines to achieve efficient network communication, we first need to understand some basic concepts, including the following
