Socket is a window that communicates with servers and clients **. ServerSocket and Socket are used for socket communication. ServerSocket package information: https://docs.oracle.com/javase/jp/7/api/java/net/ServerSocket.html Socket package information: https://docs.oracle.com/javase/jp/7/api/java/net/Socket.html
ServerSocket variable name = new ServerSocket (port number);
Socket variable name = new Socket ();
These are defined and communication is performed.
For simple communication
--Create an instance of ServerSocket --Socket communication connection --Communication started
Is the basic operation.
python
//ServerSocket instance
ServerSoket variable name_server_socket = new ServerSocket(port_number);
//Socket communication connection
Socket variable name_socket = new Socket();
Variable name_socket = Variable name_server_socket.accept();
//Start communication
~~Arbitrary processing~~
Variable name.close();
Server.java
import java.io.*;
import java.net.*;
public class Server{
private final int port;
// constructor
public Server(int port){
this.port = port;
}
public static void main(String[] args){
Server server = new Server(8080);
server.start();
}
public void start(){
try{
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("waiting for connection in this port now.");
Socket socket = new Socket();
socket = serverSocket.accept();
System.out.println("connection completed.");
socket.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
Recommended Posts