Java Network Basics (Communication)

About Socket

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.


Socket communication method

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();

The following is a sample code for communication.

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();
        }
    }
}

ezgif-2-c46a66d542f8.gif

Recommended Posts

Java Network Basics (Communication)
Java basics
Java basics
Java basics
java programming basics
Object-oriented (Java) basics
Java concurrency basics
Java programming basics practice-array
Muscle Java Basics Day 1
Basics of character operation (java)
[Java] Implementation of Faistel Network
Java programming basics practice-for statement
Summary of Java language basics
Java programming basics practice-switch statement
Getting Started with Java Basics
[Java] Server Client Communication 1 (Unfinished)
Java Development Basics ~ Exercise (Array) ~
[Java11] Stream Usage Summary -Basics-
[Java basics] What is Class?
Access the network interface in Java
I tried UDP communication with Java
Java
Try bidirectional communication with gRPC Java
Java
Java Performance Chapter 5 Garbage Collection Basics
TCP communication (socket communication) in Java (ASCII, Binary)
[# 1 Java] Basics of Java-Major premise before studying-
Memo when HTTP communication with Java (OkHttp)
[day: 5] I summarized the basics of Java
Looking back on the basics of Java
Basics of java basics ② ~ if statement and switch statement ~