Sokcetを使って通信

使っていないと、すぐに使い方を忘れてしまうのでサンプルで作ったプログラムごとメモしておく。

サーバプログラム

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

public class SocketListenerSample {
	
	public static void main(String[] args) throws Exception {
		int port = Integer.parseInt(args[0]);
		SocketListenerSample listener = new SocketListenerSample(port);
		listener.startListen();
	}

	private int bindPort;

	public SocketListenerSample(int bindPort) {
		this.bindPort = bindPort;
	}
	
	public void startListen() throws IOException {
		
		
		ServerSocket server = null;
		try {
			server = new ServerSocket(bindPort);
			
			InetSocketAddress address = (InetSocketAddress) server.getLocalSocketAddress();

			System.out.println("ポート:" + bindPort + "をリッスンします。");
			System.out.println("CTR-Cで止めてください。");

			while (true) {
				Socket socket = server.accept();
				socket.setSoTimeout(500);
				BufferedReader in = null;
				try {
					in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

					System.out.println("-------------------------------------------");
					System.out.println("受信日時:" + new java.util.Date());
					System.out.println("受信したデータ: ");

					String line = null;
					while ((line = in.readLine()) != null) {
						System.out.println("   " + line);
					}
				} catch (SocketTimeoutException ste) {
					// 受信ソケットから指定した時間応答がない場合は強制的にソケットを閉じる。
				} finally {
					if (in != null) in.close();
					if (socket != null) socket.close();
				}
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			if (server != null) server.close();
		}
	}
}

クライアントプログラム

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

public class SocketSample {

	public static void main(String[] args) throws Exception {
		String host = args[0];
		int port = Integer.parseInt(args[1]);
		String message = args[2];
		
		SocketSample sender = new SocketSample(host, port);
		sender.execute(message + "[SEND DATE:" + new java.util.Date() + "]");
	}
	
	private String host;
	private int port;
	
	public SocketSample(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void execute(String message) throws IOException {
		Socket socket = null;
		try {
			socket = new Socket(host, port);

			OutputStream out = null;
			try {
				out = socket.getOutputStream();
				PrintWriter writer = new PrintWriter(out);
				writer.println(message);
				writer.flush();
			} finally {
				if (out != null) out.close();
			}
		} catch (IOException se) {
			se.printStackTrace();
		} finally {
			if (socket != null) socket.close();
		}
	}
}