Created
May 29, 2014 11:49
-
-
Save hoshi-takanori/33b3a060e7502f7be836 to your computer and use it in GitHub Desktop.
ちょーかんたんなサーバー。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
/** | |
* ちょーかんたんなサーバー。 | |
*/ | |
public class Server { | |
/** | |
* ポート番号。 | |
*/ | |
public static final int PORT = 1234; | |
/** | |
* サーバーの処理を行う。 | |
* @throws IOException 入出力エラー | |
*/ | |
public void start() throws IOException { | |
// ポートを開く | |
ServerSocket listener = new ServerSocket(PORT); | |
System.out.println("opened port " + PORT); | |
while (true) { | |
// クライアントからの接続を待つ。 | |
Socket socket = listener.accept(); | |
System.out.println("connected from " + socket.getInetAddress()); | |
// 入出力ストリームを読み書きする準備。 | |
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); | |
PrintStream writer = new PrintStream(socket.getOutputStream(), true, "UTF-8"); | |
// クライアントからのリクエストを受信する (ブロッキング I/O)。 | |
String request = reader.readLine(); | |
System.out.println("received '" + request + "'"); | |
// クライアントにレスポンスを送信する。 | |
if (request.equals("HELLO")) { | |
writer.println("WELCOME"); | |
System.out.println("responded 'WELCOME'"); | |
} | |
// 後始末。 | |
socket.close(); | |
System.out.println("connection closed"); | |
} | |
} | |
/** | |
* main メソッド。 | |
* @param args コマンドライン引数 | |
*/ | |
public static void main(String[] args) { | |
try { | |
new Server().start(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment