Home >Java >javaTutorial >Detailed explanation of examples of network communication

Detailed explanation of examples of network communication

零下一度
零下一度Original
2017-06-25 09:33:031651browse

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 protocol

The 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 protocol

A 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 multiple

applications 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 the

output 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn