JAVA - 61. Network connection

Posted by sirfartalot on Wed, 22 Jan 2020 17:11:13 +0100

How the chat program works:
1. Client connects to server
2. The server establishes a connection and adds users to the guest list
3. Another user connects to the server
4. User a sends the information to user b through the server, and at the same time receives the reply from user b

[location server] use Socket or ip address (4 numbers between 0 and 255) to locate the server
[java.net.Socket] java.net contains most of the interfaces and implementation classes of network programming; socket is the socket of the client, which is composed of ip address + port number (each port number can realize a service); while ServerSocket in java.net.ServerSocket is the socket of the server; a connection can be created between two sockets
Exercise 1. Establish a network connection and connect the client to the server

Server:

import java.net.*;
import java.io.IOException;

public class Server{
        private ServerSocket serverSocket;

        public Server(){
                try{
                        serverSocket=new ServerSocket(1056);//1056 represents the port number of the computer, which means that the server provides services on port 1056 of the local computer
                        System.out.println("server started......");
                        Socket client=serverSocket.accept();
                       //Listen for client connections. If the connection to the client is not monitored, the method will be suspended here. Only when the connection to the client is monitored, the accept method will be completed
                        System.out.println("A client is connected to the server");
                }catch(IOException e){
                        e.printStackTrace();
                }
        }
        public static void main(String[] args){
                new Server();
        }
}

Client:

import java.net.*;
import java.io.IOException;

public class Client{
          private Socket clientSocket;

          public Client(){
                    try{
                       clientSocket=new Socket("127.0.0.1",1056);
                       //Because the server is on the local machine, the ip address is 127.0.0.1, and the port number is 1056. If this sentence is executed successfully, it means that the server has been connected
                       System.out.println("The client is connected to the server");
                    }catch(IOException e){
                        e.printStackTrace();
                    }
          }

          public static void main(String[] args){
                    new Client();
          }
}


Topics: socket Java network Programming