Three elements of network
ip address: the unique identification of the device in the network
ipv4: it is composed of 4 bytes and is expressed in dotted decimal system
Example: 192.168.66.202
ipv6: it is composed of 16 bytes and is expressed in bold hexadecimal
Example: fb34:66:77:ac:3f
Common commands:
ipconfig: view the ip address of this machine
ping: check whether the network and the specified ip are connected
Port number: represents the application program on a host. It is an integer within the range of [065535].
Port numbers from 0 to 1023 may be occupied. It is recommended to use port numbers after 1024.
Protocol: Rules for data transmission in a network
UDP: for connectionless and insecure protocols, 64KB data is transmitted each time
TCP: for connected and secure protocols, there is no limit on the size of transmitted data.
InetAddress class
public static InetAddress getByName(String host)
Determine the IP address of the host given the host name.
public String getHostAddress()
Return the IP address string (expressed as text), for example: "192.168.83.44"
public String getHostName()
Gets the host name of this IP address.
//Get ip address object
InetAddress inetAddress = InetAddress.getByName("192.168.83.192");
//Get host address
String address = inetAddress.getHostAddress();
//Get host name
String hostName = inetAddress.getHostName();
UDP communication
UDP sender
1. Create DatagramSocket object (dock)
2. Create DatagramPacket object (package)
ip address and port number need to be specified
3. Call the send method to send data (deliver the package to the wharf)
4. Call the close method to release resources (close the dock)
public class Sender { public static void main(String[] args) throws IOException { //1. Create DatagramSocket object (dock) DatagramSocket ds=new DatagramSocket(); //2. Create DatagramPacket object (package) //Ready to send data System.out.println("Please enter the data to send:"); String str = sc.next(); byte[] bs=str.getBytes(); //Length of data sent int len=bs.length; //Specify the ip address to receive String ip="127.0.0.1"; //Specify the port number to receive int port=10086; DatagramPacket packet=new DatagramPacket(bs,len, InetAddress.getByName("127.0.0.1"),port); //3. Call the send method to send data (deliver the package to the wharf) ds.send(packet); //4. Call the close method to release resources (close the dock) ds.close(); } }
UDP receiver
public class Receiver { public static void main(String[] args) throws IOException { //1. Create DatagramSocket object (dock) DatagramSocket ds=new DatagramSocket(10086); //2. Create DatagramPacket object (new package) byte[] bs=new byte[1024]; DatagramPacket packet=new DatagramPacket(bs,bs.length); //3. Receive data and store it in the package ds.receive(packet); //Blocking, waiting for the sender to send data //4. Open the package and get the data byte[] data = packet.getData(); //Get byte array int length = packet.getLength(); //Gets the actual length of the data InetAddress address = packet.getAddress(); //Get the ip address of the sender //Converts the received data into a string String str=new String(data,0,length); System.out.println(address.getHostAddress()+"...."+str); //5. Release resources ds.close(); } }
Three communication modes
Unicast: one sender sends one receiver Send and receive using datagram socket Multicast: one sender sends to multiple receivers (one group) //Create MulticastSocket object MulticastSocket ms=new MulticastSocket(10000); //Add the current address to the group: multicast address: 224.0.1.0 ms.joinGroup(InetAddress.getByName("224.0.1.0")); Broadcast: one sender sends it to all receivers //Broadcast address: 255.255.255.255 Send and receive using datagram socketTCP communication
Basic principle of TCP communication
![](/images/blog/c021ad13f37d01e55def3e4c889553e4.jpg)
client
public class TCPClient { public static void main(String[] args) throws IOException { //Create a Socket object and specify the ip address and port number of the server Socket socket=new Socket("127.0.0.1",10086); //Get output stream OutputStream out = socket.getOutputStream(); //Network server write data out.write("Hello world".getBytes()); //Tell the server that it is finished. socket.shutdownOutput(); //Get input stream BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream())); String s = br.readLine(); System.out.println(s); //Release resources socket.close(); } }
Server
public class TCPServer { public static void main(String[] args) throws IOException { //Create ServerSocket object ServerSocket server=new ServerSocket(10086); //Listening client (welcome) Socket socket = server.accept(); //block //Get input stream InputStream in = socket.getInputStream(); byte[] bs=new byte[1024]; int len; while ((len=in.read(bs))!=-1){ String str=new String(bs,0,len); System.out.println(str); } //Get output stream BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write("HelloWorld"); bw.newLine(); //Line feed bw.flush(); //Release resources socket.close(); server.close(); } }
File upload case
client
public class UploadClient { public static void main(String[] args) throws IOException { //Create a Socket object and bind the ip and port number of the server Socket socket=new Socket("127.0.0.1",10010); //Get the output stream to the server OutputStream out = socket.getOutputStream(); //Read local a.jpeg pictures FileInputStream fis=new FileInputStream("day15/a.jpeg"); byte[] bs=new byte[1024]; int len; //Record the number of bytes read each time while ((len=fis.read(bs))!=-1){ //Write the read data to the server out.write(bs,0,len); } //Tell the server that the data has been written socket.shutdownOutput(); //Get the data returned by the server BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String s = br.readLine(); System.out.println(s); //Release resources socket.close(); } }
Server
public class UploadServer { public static void main(String[] args) throws IOException { //Create the server ServerSocket object and bind the port number ServerSocket server=new ServerSocket(10010); //Listening client Socket socket = server.accept(); //Create local output stream File filename=new File("/Users/itheima/Desktop/upload", UUID.randomUUID()+".jpeg"); FileOutputStream fos=new FileOutputStream(filename); //Gets the stream that reads network data InputStream in = socket.getInputStream(); byte[] bs=new byte[1024]; int len; //Record the number of bytes read each time while ((len=in.read(bs))!=-1){ //Write the read data to the server fos.write(bs,0,len); } fos.close(); //Write a feedback message to the server "upload succeeded" BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write("Upload succeeded"); bw.newLine(); bw.flush(); socket.close(); server.close(); } }
Server multithreading optimization
/* Image upload thread task */ public class UploadRunnable implements Runnable { private Socket socket; public UploadRunnable(Socket socket) { this.socket = socket; } @Override public void run() { try { //Create local output stream File filename=new File("/Users/itheima/Desktop/upload", UUID.randomUUID()+".jpeg"); FileOutputStream fos=new FileOutputStream(filename); //Gets the stream that reads network data InputStream in = socket.getInputStream(); byte[] bs=new byte[1024]; int len; //Record the number of bytes read each time while ((len=in.read(bs))!=-1){ //Write the read data to the server fos.write(bs,0,len); } fos.close(); //Write a feedback message to the server "upload succeeded" BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write("Upload succeeded"); bw.newLine(); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Endless loop monitoring client, constantly processing the task of file upload
public class UploadServer { public static void main(String[] args) throws IOException { //Create the server ServerSocket object and bind the port number ServerSocket server=new ServerSocket(10010); while (true){ //Listening client Socket socket = server.accept(); //block //Create thread and execute new Thread(new UploadRunnable(socket)).start(); } //server.close(); } }
public String calc(String name){ int num = name.hashCode()%10; switch(num){ case 1: return "The Yintang is black and bloody"; case 2: return "You're lucky today. Remember to celebrate"; case 3: return "I must owe you in my last life. Don't let me see you. Go, go...."; case 4: return "Here's a two-color ball number 06 08 13 18 26 33 + 10 Win the prize"; case 5: return "You may find money when you go out tomorrow"; case 6: return "Your character is worrying. Do more good deeds"; case 7: return "It stinks. It feels like you stepped on shit🐶"; case 8: return "Handsome boy, I think you're going to have good luck. Take me"; case 9: return "Marry Bai Fumei and go to the peak of life"; } }