1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaでTCP通信によるデータ送受信

Last updated at Posted at 2021-08-31

TCP通信特徴

データー送信側(クライアント)

Socket クラスでデータ送受信を行う。
Socket sock = new Socket(IPアドレスまたはホスト名,ポート番号);

Client.java
package com.maekawa.base;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1,接続したいサーバーの住所(IP、ポート)
            InetAddress serverIp = InetAddress.getByName("google.com");
            int port = 8080;
            //2,接続作成
            socket = new Socket(serverIp, port);
            //3,ioストリーム送る
            os = socket.getOutputStream();
            os.write("Hello world".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4,接続を遮断する
            socket.close();
            os.close();
        }
    }
}

データ受信側(サーバー)

Server.java
package com.maekawa.base;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            //1,接続を受け付けるポート設定
            ServerSocket serverSocket = new ServerSocket(8080);
            //2,接続準備
            Socket socket = serverSocket.accept();
            //3,クライアントからのデータを読み込む
            InputStream io = socket.getInputStream();

            ByteArrayOutputStream data = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len=io.read(buffer))!=-1){
                data.write(buffer,0,len);
            }
            System.out.println(data.toString());

            //4,接続を切断する
            io.close();
            socket.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

参考記事

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?