簡易Javaネットワークプログラミング

Facebook にシェア
このエントリーをはてなブックマークに追加
[`livedoor` not found]
Delicious にシェア

Javaでsocket機能を使用した非常に簡易なネットワークプログラムを作りました。
ありきたりですが、Clientから郵便番号をリクエストすると、Serverから対応する住所情報をレスポンスします。
郵便データは、日本郵便 郵便データダウンロードから事前取得し、Server起動時に読み込むような非常に簡易なプログラムです。

1. Server Code

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;

public class OriginalServer {

	public HashMap<String, String> map;
	private String file;

	public OriginalServer(String file) {
		this.file = file;
	}

	public void read() {

		try {
			File f = new File(file);
			byte[] b = new byte[(int) f.length()];
			FileInputStream fi = null;
			fi = new FileInputStream(f);
			fi.read(b);
			String str = new String(b);
			String[] strrec = str.split("n");

			System.out.println("To be prepared.....");

			String[] workArray;
			map = new HashMap<String, String>();
			for (int i = 0; i < strrec.length; i++) {
				workArray = strrec[i].split(",");
				map.put(workArray[2].replace(""", ""),
						workArray[6].replace(""", "")
								+ workArray[7].replace(""", "")
								+ workArray[8].replace(""", ""));
			}

			System.out.println("Wait for request.....");

		} catch (FileNotFoundException e) {
			System.out.println("File Not Found Error");
			System.exit(-1);
		} catch (IOException e) {
			System.out.println("File Read Error");
			System.exit(-1);
		}
	}

	public static void main(String args[]) {
		try {
			ServerSocket serverSocket = new ServerSocket(
					Integer.parseInt(args[0]));

			OriginalServer os = new OriginalServer(args[1]);

			// read address-File
			os.read();

			while (true) {
				Socket socket = serverSocket.accept();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));

				String post;
				while ((post = reader.readLine()) != null) {
					// readline() + Empty() = Start HTTP-BODY
					if (post.isEmpty()) {
						post = reader.readLine().replace("-", "");
						break;
					}
				}
				String addr;
				if (os.map.containsKey(post)) {
					addr = "〒" + post.substring(0, 3) + "-"
							+ post.substring(3, post.length()) + " -> "
							+ os.map.get(post) + "n";
				} else {
					addr = "There is no postal code.n";
				}

				PrintStream writer = new PrintStream(socket.getOutputStream());

				writer.print("HTTP/1.1 200 OKn");
				writer.print("Connection: closen");
				writer.print("Content-Length: " + addr.length() + "n");
				writer.print("Content-Type:text/plainnn");
				writer.print(addr);
				writer.flush();
				writer.close();
				reader.close();
				socket.close();
			}
		} catch (SocketException e) {
			System.out.println("Socket Error");
			System.exit(-1);
		} catch (IOException e) {
			System.out.println("IO Error");
			System.exit(-1);
		}
	}
}

2. Client Code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class OriginalClient {

	public static void main(String args[]) {
		try {

			Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));

			writer.write("GET / HTTP/1.1rn");
			writer.write("Host: " + args[0] + ":" + args[1] + "rn");
			writer.write("Connection: closern");
			writer.write("rn");
			writer.write(args[2] + "rn");
			writer.flush();

			String line;
			while ((line = reader.readLine()) != null) {
				if (line.isEmpty()) {
					System.out.println(reader.readLine());
				}
			}

			writer.close();
			reader.close();
			socket.close();

		} catch (UnknownHostException e) {
			System.out.println("Host not found");
			System.exit(-1);
		} catch (SocketException e) {
		} catch (IOException e) {
			System.out.println("IO error");
			System.exit(-1);
		}
	}
}

3. 実行結果: Server

C:hogenetworkPog > java OriginalServer 12345 KEN_ALL.CSV
To be Prepared....
Wait for request....

4. 実行結果: Client

C:hogenetworkPog > java OriginalClient localhost 12345 1400011
〒140-0011 -> 東京都品川区東大井

以上です。