TCPクライアントの例

GoogleにTCPで接続してレスポンス取得するだけのサンプルです。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.Charset;

public class TcpClient {
    private String host;
    private int port;
    private Socket socket;
    
    public TcpClient(String host, int port) throws IOException {
        this.host = host;
        this.port = port;
    }
    public void connect() {
        try {
            socket = new Socket(host, port);
            initSocket();
            doConversation();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    protected void initSocket() throws IOException {
        socket.setSoTimeout(30*1000); // 30sec
        try {
            socket.setTcpNoDelay(true);
        } catch (SocketException e) {
            // do-nothing
        }
    }
    private void doConversation() throws IOException {
        sendRequest();
        receiveResponse();
    }
    protected void sendRequest() throws IOException {
        OutputStreamWriter writer = new OutputStreamWriter(
                new BufferedOutputStream(socket.getOutputStream()),
                Charset.forName("UTF-8"));
        writer.write("GET / HTTP/1.1\n");
        writer.write("Host: www.google.co.jp\n");
        writer.write("\n\n");
        writer.flush();
        socket.shutdownOutput(); // half-close
    }
    protected void receiveResponse() throws IOException {
        InputStreamReader reader = new InputStreamReader(
                new BufferedInputStream(socket.getInputStream()),
                Charset.forName("UTF-8"));
        char[] buffer = new char[8192];
        int count = -1;
        while ((count = reader.read(buffer)) >= 0) {
            System.out.println(buffer);
        }
    }

    public static void main(String[] args) throws IOException {
        new TcpClient("www.google.co.jp", 80).connect();
    }
}