Internet of things training notes_ Network programming

Keywords: http udp TCP/IP

Internet of things training notes_ Network programming

Basic concepts of network programming:

1. Computer network

A computer network is a collection of interconnected independent computers,
The simplest form of network consists of two computers.

2. Network communication

IP address:
1. Each host in the IP network must have a unique IP address; Native IP 127.0.0.1 (native address)
2.IP address is a logical address; Dynamically change the unique identification of the computer: physical address
3. The IP address on the Internet is globally unique;
4.32 bits, 4 bytes, commonly expressed in dotted decimal format, for example: 192.168.0.16.

agreement:
1. Rules, standards or conventions established for data exchange (Communication) in the network; (= semantics + syntax + rules) http;
2. Different layers have different protocols.
www.baidu.com is collectively referred to as domain name - > IP: port

Port number:
The port is represented by a 16 bit number. Its range is 0 – 655351024. Port numbers below 24 are reserved for predefined services. For example, http uses port 80.
ip: finding hosts
port: find the corresponding service on the host
Port number
gmail(google Mail System) smtp 587 pop3 995
HTTP (hypertext protocol web access) 80
SMTP 25 pop3 (mail protocol) 110 smtp and pop3 are mail sending and receiving protocols
Telnet (remote login) 23 client login to server-side protocol
FTP (file upload and download) port 21 is responsible for initiating and establishing the connection between the two sides, and port 20 is responsible for transmitting data!

3. OSI(Open System Interconnection) reference model

Physical layer: binary transmission, which determines how to transfer the bit stream on the communication channel;
Data link layer: strengthen the transmission function of the physical layer and establish an error free transmission line;
Network layer: there are many lines for data to reach the destination in the network. The network layer is responsible for finding the best transmission line;
Transport layer: the transport layer provides reliable data transmission services from the source computer to the destination computer, isolates the upper and lower layer protocols of the network, and makes the protocols of the upper layer network applications independent of the lower layer;
Session level meeting: establish, organize and coordinate the communication between two mutually communicating application processes;
Presentation layer: it deals with the presentation of the transmitted data, that is, the syntax and semantics of the information. If necessary, it will use a common format to convert in a variety of formats;
Application layer: provide network communication services for users' applications;

The OSI(Open System Interconnection) reference model is not a physical entity with these seven layers, but a function division. It is an abstract reference model. During network communication, each layer provides the corresponding functions of this layer;
1. Direct communication is not allowed between peer layers of communication entities. They are virtual communication, and the actual communication is completed at the bottom layer;
2. Strict one-way dependence between layers;
3. The upper layer uses the service provided by the lower layer - Service user;
4. The lower layer provides services to the upper layer - Service provider.
5. Virtual communication between peer-to-peer entities;
6. The lower layer provides services to the upper layer, and the actual communication is completed at the bottom layer.

4. Protocols used by OSI layers

1. Application layer: remote login protocol Telnet, file transfer protocol FTP (this protocol will be used when downloading a software or material on the Internet), Hypertext Transfer Protocol HTTP (this protocol is used more often when browsing a web page through IE), Domain Name Service DNS (it is widely used. Generally, access to a computer through the network does not use the IP address of the host, but through the domain name of the host), Simple Mail Transfer Protocol SMTP (sending mail through Foxmail), post office protocol POP3, etc. (receiving mail through Foxmail);

2. Transport layer: transmission control protocol TCP, user datagram protocol UDP;
TCP: a reliable connection oriented transmission protocol. When using TCP protocol for communication, first establish the connection between the two sides through three-step handshake. Once the connection is established, you can communicate. TCP protocol provides a mechanism for data confirmation and retransmission to ensure that the data can reach the data receiving end. Like making a phone call.

UDP: it is a connectionless and unreliable transmission protocol. When using UDP protocol for communication, there is no need to establish a connection, and you can directly send data to an IP address. As for whether it can be received, there is no guarantee that the data may be lost in the sending process, the IP address may not exist, and the host represented by the IP address may not be running.

3. Network layer: Internet Protocol IP, Internet Control Message Protocol ICMP, Internet Group Management Protocol IGMP.

TCP based Socket programming steps:

1. Server programming:

①call ServerSocket(int port)Create a server-side socket and bind it to the specified port;
②call accept(),Listen for connection requests. If the client requests a connection, accept the connection and return to the communication socket;
③call Socket Class getOutputStream()and getInputStream Obtain the output stream and input stream and start the transmission and reception of network data;
④Finally, close the communication socket.

2. Client programming:

①call Socket()Create a stream socket and connect to the server; Socket(ip,port)
②call Socket Class getOutputStream()and getInputStream Obtain the output stream and input stream and start the transmission and reception of network data; 
③Finally, close the communication socket.

Training code:

Simple chat code for server and client (I):

Server code:

package tcpTest;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServertClient {
	public static void main(String[] args) throws Exception {
		ServerSocket ss=new ServerSocket(1000);
		Socket socket=ss.accept();
		
		OutputStream os=socket.getOutputStream();
		DataOutputStream dos=new DataOutputStream(os);
		
		/**
		 * Input content from terminal
		 * Read the contents input by the terminal
		 * Read line by line
		 */
		InputStreamReader isr=new InputStreamReader(System.in);
		BufferedReader br=new BufferedReader(isr);
		
		InputStream is=socket.getInputStream();
		DataInputStream dis=new DataInputStream(is);
		
		while(true) {
			String str=br.readLine();
			System.out.println("Server said:"+str);
			dos.writeUTF(str);
			dos.flush();
			String msg=dis.readUTF();
			System.out.println("Client said:"+msg);
			
		}
		
	}

}

Code of receiving end:

package tcpTest;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleClient {
public static void main(String[] args) throws Exception {
	Socket socket=new Socket("127.0.0.1",1000);
	
	InputStream io=socket.getInputStream();
	DataInputStream dis=new DataInputStream(io);
	
	OutputStream os=socket.getOutputStream();
	DataOutputStream dos=new DataOutputStream(os);
	
	InputStreamReader isr=new InputStreamReader(System.in);
	BufferedReader br=new BufferedReader(isr);
	
	while(true) {
		String str=dis.readUTF();
		System.out.println("Server said:"+str);
		String msg=br.readLine();
		System.out.println("Client said:"+msg);
		dos.writeUTF(msg);
		dos.flush();
		}
	}
}

Relevant codes of data sending objects of server and customer (II)

Encapsulate object code

package WetTest;

import java.io.Serializable;

public class Student implements Serializable {
	private int id;
	private String name;
	private int age;
	
	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	
	
	
	
}

Server code

package WetTest;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
/**A brief introduction to multithreading applications
 * Client as
 * Big data requires hardware. Computers with medium performance and 16gb of memory
 * Multiple clients
 * Runable Interface or inheriting Thread, you need to override the run method
 * Inner class
 */




public class ServerTest {
	
	private ServerSocket ss;
	private Socket s;
	private InputStream is;
	private ObjectInputStream ois;
	
	public static void main(String[] args) {
		ServerTest st=new ServerTest();//Take the class outside first
		Handler handler=st.new Handler();//Then the inner class in new
		handler.start();
	}
	
	
	public void shutdown() throws Exception {
		if(ois!=null)ois.close();
		if(is!=null)is.close();
		if(s!=null)s.close();
		if(ss!=null)ss.close();
	}
	
	
//Inner class
	private class Handler extends Thread{
		//Override run()
		public void run() {
			System.out.println("The server is turned on,Waiting for connection");
			try {
				ss=new ServerSocket(10001);
				s=ss.accept();
				System.out.println("Connection completed");
				is=s.getInputStream();
				ois=new ObjectInputStream(is);
				System.out.println("Data start acceptance...");
				List<Student> list=(List<Student>) ois.readObject();
				System.out.println("Data received,Start printout...");
				for(Student s:list) 
				{System.out.println(s);}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				shutdown();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			
		}
		
	}
		
}

Client code

package WetTest;
//send data

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.LineListener;

public class ClientTest {
	public static void main(String[] args) throws Exception {
		Socket socket=new Socket("127.0.0.1",10001);
		//Read from the file, package and send it
		
		//Because the reading is row by row, you want to read row by row
		FileReader fr=new FileReader("C:\\Users\\daier\\eclipse-workspace\\TCPtest\\src\\WetTest\\test.txt");
		BufferedReader br=new BufferedReader(fr);
		
		String str=null;
		String [] s=null;
		Student student=null;
		ArrayList<Student> list=new ArrayList<Student>();
		
		while((str=br.readLine())!=null) {
			s=str.split("[:]");//Colon is the key word of java, so []
			student =new Student(Integer.parseInt(s[0]),s[1],Integer.parseInt(s[2]));
			System.out.println(student);
			list.add(student);
		}
		System.out.println("Establish the connection between the client and the server");
		//send data
		OutputStream os=socket.getOutputStream();
		ObjectOutputStream oos=new ObjectOutputStream(os);//Remember to serialize the sent object to an interface that inherits Seria or something
		oos.writeObject(list);
		oos.flush();
		System.out.println("The client completes the sending task");
		
		
	}
}

Summary

You need to pay attention to the port number in network programming. Sometimes the port number will be occupied. At this time, you need to change the port. You can use the secret order in the cmd window
netstat -ano to list all port usage
netstat -aon|findstr port number, find the port details and the PID value of the corresponding process
tasklist|findstr "PID value" to view the process details
You can then close the corresponding PID process in the task manager

Pay attention to the coding format of the transmitted data. Sometimes the characters are not equal because of the coding format

java does not directly provide a method to delete the contents of the document. My solution is to traverse the file to be read and write it to a new file. Write an article in the new file to complete deletion and modification

Posted by kid_drew on Fri, 24 Sep 2021 16:46:28 -0700