Skip to content

Instantly share code, notes, and snippets.

@hiroshiro
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save hiroshiro/2f09f11707d985f972c1 to your computer and use it in GitHub Desktop.

Select an option

Save hiroshiro/2f09f11707d985f972c1 to your computer and use it in GitHub Desktop.
ソケットクライアント&サーバーtimeoutを使う。
import java.util.*;
import java.io.*;
import java.net.*;
public class myservertimeout {
private static final int LISTEN_PORT = 9000;
private static final int ACCCEPT_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 5000;
public static void main(String[] args){
ServerSocket ssock = null;
Socket sock = null;
try{
ssock = new ServerSocket(LISTEN_PORT);
ssock.setSoTimeout(ACCCEPT_TIMEOUT);
sock = ssock.accept();
sock.setSoTimeout(READ_TIMEOUT);
Reader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Writer out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
StringBuilder sb = new StringBuilder(4096);
int c;
while ((c = in.read()) != -1){
if(c == '.'){
break;
}
sb.append((char)c);
}
out.write(sb.toString());
out.flush();
System.out.println(sb);
} catch (SocketTimeoutException e) {
System.err.println("timeout");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (sock != null) {
sock.close();
}
if (ssock != null ) {
ssock.close();
}
} catch (IOException e) {}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment