Summary of Java communication API (3) How to use SocketChannel

1. 1. Introduction

This time, I will briefly summarize how to use SocketChannel. Please refer to the flow as follows.

--Client

  1. Connect the server via SocketChannel
  1. Prepare a data buffer and write / read to the server
  1. Close Socket Channel

--Server

  1. Bind iP address and port
  1. Get an instance of SocketChannel with the ServerSocketChannelImpl.accept () method
  1. Prepare a data buffer and write / read to the client
  1. Close SocketChannel and ServerSocketChannel

Then, let's make a communication demo of the client and the server from here.

2. client

The source code is as follows.

package socketchannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class WebClient {
  public static void main(String[] args) throws IOException {

//1. Let's create a SocketChannel instance with the SocketChannel open () method SocketChannel socketChannel = SocketChannel.open();

// 2. Connect to the server socketChannel.connect(new InetSocketAddress("127.0.0.1", 3333));

// 3. Prepare the data to be sent to the server ByteBuffer writeBuffer = ByteBuffer.allocate(128); writeBuffer.put("hello WebServer this is from WebClient".getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); ByteBuffer readBuffer = ByteBuffer.allocate(128); socketChannel.read(readBuffer); StringBuilder stringBuffer=new StringBuilder();

// 4. Receive data from the server readBuffer.flip(); while (readBuffer.hasRemaining()) { stringBuffer.append((char) readBuffer.get()); } System.out.println ("Message from server:" + stringBuffer); socketChannel.close(); } }

3. 3. server

The source code on the server side is as follows.

package socketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class WebServer {
public static void main(String args[]) throws IOException {
    try {

// 1. Create an instance of ServerSocketChannel with the open () method of ServerSocketChannel ServerSocketChannel ssc = ServerSocketChannel.open();

//2. Bind ip and port ssc.socket().bind(new InetSocketAddress("127.0.0.1", 3333));

//ServerSocketChannelImplのaccept()メソッドでSocketChannelインスタンスをもらってクライアントへの書き読み SocketChannel socketChannel = ssc.accept();

// 3. Prepare the data to export ByteBuffer writeBuffer = ByteBuffer.allocate(128); writeBuffer.put("hello WebClient this is from WebServer".getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); ByteBuffer readBuffer = ByteBuffer.allocate(128);

////4. Prepare the data to read socketChannel.read(readBuffer); StringBuilder stringBuffer=new StringBuilder();

        readBuffer.flip();
        while (readBuffer.hasRemaining()) {
            stringBuffer.append((char) readBuffer.get());
        }

System.out.println ("Receive data from client:" + stringBuffer); socketChannel.close(); ssc.close(); } catch (IOException e) { e.printStackTrace(); } } }

Well, if you run the above demo and it works, the result will be: サーバー

4. Finally

Thank you for reading to the end.

Recommended Posts

Summary of Java communication API (3) How to use SocketChannel
Summary of Java communication API (1) How to use Socket
Summary of Java communication API (2) How to use HttpUrlConnection
[Java] [Maven3] Summary of how to use Maven3
[java] Summary of how to handle char
[java] Summary of how to handle character strings
How to use Java API with lambda expression
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use java Optional
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
[Java] How to use compareTo method of Date class
Summary of how to implement default arguments in Java
How to use Java HttpClient (Get)
How to use Java HttpClient (Post)
[Java] How to use join method
How to use setDefaultCloseOperation () of JFrame
[Processing × Java] How to use variables
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
How to use trained model of tensorflow2.0 with Kotlin / Java
How to use JSON data in WebSocket communication (Java, JavaScript)
[Must-see for apprentice java engineer] How to use Stream API
How to call and use API in Java (Spring Boot)
Summary of how to use the proxy set in IE when connecting with Java
How to make a Java calendar Summary
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
[Java] How to use the hasNext function
How to use submit method (Java Silver)
[Java] How to use the HashMap class
Summary of how to write annotation arguments
[Easy-to-understand explanation! ] How to use Java instance
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
How to use Java classes, definitions, import
[Easy-to-understand explanation! ] How to use Java polymorphism
[Processing × Java] How to use the class
How to use Java Scanner class (Note)
[Ruby on Rails] "|| =" ← Summary of how to use this assignment operator
[Processing × Java] How to use the function
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Java] How to use the Calendar class
[Java] Learn how to use Optional correctly
[Easy-to-understand explanation! ] How to use Java overload
try-catch-finally exception handling How to use java
[Easy-to-understand explanation! ] How to use Java encapsulation
[Java] How to use substring to cut out a part of a character string