I tried to implement TCP / IP + BIO with JAVA

This article uses Java 10.0.1 installed on WIN10.

Introduction

OSI's Layer 4 (transport) protocols, TCP and UDP, are often used to communicate between systems. The benefits of TCP and UDP are: TCP --High reliability UDP --Fast speed In addition, TCP and UDP can communicate between systems, but other than that, some I / O processing must be performed on the data to be communicated, so an I / O processing method is also required. Blocking and (BIO) or non-blocking (NIO) are often used here. This time, I will implement communication between systems with TCP / IP + BIO.

Implementation#

A library called ** socket ** is used for TCP communication. We provide ** Socket ** and ** ServerSocket ** from Java language, so this time we will implement TCP / IP + BIO using these. (Official API is here: Socket, ServerSocket /javase/jp/6/api/java/net/ServerSocket.html)) ** Server-side files (actually local) **

*** Create a socket and listen for client-side access *** TcpServer file contents:


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

public class TcpServer{
    public static void main (String[] argv) throws Exception{
        try (
            //8001 Create port number
            ServerSocket server = new ServerSocket(8001);
            FileOutputStream fos = new FileOutputStream("server_recv.txt");
            FileInputStream fis = new FileInputStream("server_send.txt");
        ){
            System.out.println("wait access...");
            //Wait for client-side access
            Socket socket = server.accept();
            System.out.println("client access.");

            int ch;
            //Server the stream passed from the client side_recv.Write in txt
            InputStream input = socket.getInputStream();
            while ((ch = input.read()) != 0) {
                fos.write(ch);
            }
            // server_send.Pass the content stream written in txt to the client side
            OutputStream output = socket.getOutputStream();
            while ((ch = fis.read()) != -1) {
                output.write(ch);
            }
            //Access end
            socket.close();
            System.out.println("accsess closed.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

server_send.txt File contents:

server_send

server_recv.txt is an empty file

** Client-side files **

*** Create a socket and access the specified server and port *** TcpClient file contents:


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

public class TcpClient{
    public static void main (String[] argv) throws Exception{
        try (
            //8001 Access port number
            Socket socket = new Socket("localhost", 8001);
            FileOutputStream fos = new FileOutputStream("client_recv.txt");
            FileInputStream fis = new FileInputStream("client_send.txt");
        ){

            int ch;
            // client_send.Pass the content stream written in txt to the server side
            OutputStream output = socket.getOutputStream();
            while ((ch = fis.read()) != -1) {
                output.write(ch);
            }
            //Pass "Transfer completed!" To the server side
            output.write(0);
            //Client the stream passed from the server side_recv.Write in txt
            InputStream input = socket.getInputStream();
            while ((ch = input.read()) != -1) {
                fos.write(ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

client_send.txt File contents:

client_send

client_recv.txt is an empty file

Run

Compile TcpClient.java and TcpServer.java respectively in javac and run in java

--Run TcpServer.class

Starting the server and waiting for a connection on the client side:

PS C:\Users\ma\Documents\work\javaweb\1> java TcpServer
wait access...

--Run TcpClient.class

Start the client and access the server side:

PS C:\Users\ma\Documents\work\javaweb\1> java TcpClient

The server terminates after processing the connection from the client side:

PS C:\Users\ma\Documents\work\javaweb\1> java TcpServer
wait access...
client access.
accsess closed.
PS C:\Users\ma\Documents\work\javaweb\1>

Result verification

server_recv.txt File contents:

client_send

I was able to verify that the content passed from the client side (client_send.txt) is overwritten.

client_recv.txt also overwrote the contents (server_send.txt) passed from the server side:

server_send

Summary

This time, I made a TCP / IP + BIO transfer path using Java Socket and ServerSocket libraries. We also verified that data can be sent bidirectionally between the server and the client.

reference#

  1. Kazuya Maebashi. 2016. Introduction to Web application development from the basics. Technical Review Company.

Recommended Posts

I tried to implement TCP / IP + BIO with JAVA
Try to implement TCP / IP + NIO with JAVA
I tried to interact with Java
I tried to implement Stalin sort with Java Collector
I tried to implement ModanShogi with Kinx
I tried to make Basic authentication with Java
I tried to implement deep learning in Java
I tried to break a block with java (1)
I tried to implement file upload with Spring MVC
I tried to implement Firebase push notification in Java
[Java 11] I tried to execute Java without compiling with javac
[Java] I tried to implement Yahoo API product search
I tried to implement the Euclidean algorithm in Java
I tried UDP communication with Java
I tried to summarize Java learning (1)
I tried to summarize Java 8 now
I tried to create a java8 development environment with Chocolatey
[Rails] I tried to implement batch processing with Rake task
I want to implement various functions with kotlin and java!
I tried to summarize Java lambda expressions
I tried to get started with WebAssembly
I tried to implement the image preview function with Rails / jQuery
I tried to implement flexible OR mapping with MyBatis Dynamic SQL
I tried to implement the Iterator pattern
I tried using OpenCV with Java + Tomcat
I tried to make an Android application with MVC now (Java)
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image
I tried to implement polymorphic related in Nogizaka.
I tried to manage struts configuration with Coggle
I tried to manage login information with JMX
java I tried to break a simple block
I want to use java8 forEach with index
I tried to output multiplication table in Java
I tried to create Alexa skill in Java
I tried to implement a server using Netty
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
I tried what I wanted to try with Stream softly.
I tried to read and output CSV with Outsystems
[Java] I tried to solve Paiza's B rank problem
I tried to operate SQS using AWS Java SDK
# 2 [Note] I tried to calculate multiplication tables in Java.
I started MySQL 5.7 with docker-compose and tried to connect
I tried to get started with Spring Data JPA
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to draw animation with Blazor + canvas API
I tried OCR processing a PDF file with Java
I want to transition screens with kotlin and java!
~ I tried to learn functional programming in Java now ~
I want to get along with Map [Java beginner]
I used to make nc (netcat) with JAVA normally
roman numerals (I tried to simplify it with hash)
I tried to find out what changed in Java 9
I tried to create a shopping site administrator function / screen with Java and Spring
When I tried to unit test with IntelliJ, I was told "java.lang.OutOfMemoryError: Java heap space"
[Swift] I tried to implement Instagram profile-like UI with UICollectionView only with code without storyboard
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
I tried DI with Ruby
Java to play with Function
I tried Drools (Java, InputStream)