Skip to content

Instantly share code, notes, and snippets.

@chomado
Last active December 26, 2015 10:59
Show Gist options
  • Save chomado/7140299 to your computer and use it in GitHub Desktop.
Save chomado/7140299 to your computer and use it in GitHub Desktop.
localhostの13番ポートで動作しているDaytimeサーバに接続するクライアント
import java.net.*;
import java.io.*;
public class DaytimeText {
boolean isOK = false;
String host;
Socket sock;
public DaytimeText(String host, int port) {
try {
this.host = host;
sock = new Socket(host, port);
isOK = true;
} catch (UnknownHostException e) {
System.err.println("unknown host : " + host);
} catch (NoRouteToHostException e) {
System.err.println("unreachable : " + host);
} catch (ConnectException e) {
System.err.println("connect refused : " + host);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void run() {
if (! isOK) {
System.exit(1);
}
try {
BufferedReader is;
is = new BufferedReader (new InputStreamReader (sock.getInputStream())); // ソケットの中からInputStreamを取り出している
String s;
while ((s = is.readLine()) != null) {
System.out.println(host + ":" + s);
}
sock.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
public class RunDaytimeText {
public static void main(String[] args) {
DaytimeText cli = new DaytimeText("localhost", 13);
cli.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment