そこにない問題を追いかけるのに何時間も費やすとき、あなたはそれを嫌いではありませんか?Stephen CIにSSCCEを提供しようとしたところ、機能しているため、そのような例を提供できなかったことがわかりました。私のデバッグコードは問題を引き起こしていました...
記録のために、ここに動作するコードがあります(他の誰かが同様の問題を抱えている場合に備えて):
sscceServer.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class sscceServer
{
public static class EchoHandlerThread implements Runnable
{
private final Socket sock;
private final int id;
public EchoHandlerThread(Socket s, int i)
{
sock = s;
id = i;
}
public void run()
{
try {
//----- set socket read timeout to 10 seconds -----
sock.setSoTimeout(10000);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String input;
while ((input = in.readLine()) != null) {
System.out.println("[" + id + "] <" + input + ">");
}
out.close();
in.close();
sock.close();
System.out.println("\tConnection #" + id + " closed");
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
public static class Listener
{
private final InetAddress bindip;
private final int portnum;
public Listener(String ipstr, int pn)
{
try {
bindip = InetAddress.getByName(ipstr);
portnum = pn;
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void start()
{
try {
ServerSocket srvsock = new ServerSocket(portnum, 0, bindip);
System.out.println("Listening on " + bindip.getHostAddress() + ":" + portnum);
int connum = 0;
while (true) {
Socket sock = srvsock.accept();
connum++;
InetAddress ipaddr = sock.getInetAddress();
System.out.println("Connection #" + connum + " from: " + ipaddr.getHostAddress());
new Thread(new EchoHandlerThread(sock, connum)).start();
}
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
public static void main(String[] args)
{
Listener lsnr = new Listener("localhost", 8988);
lsnr.start();
}
}
sscceClient.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class sscceClient
{
public static void main(String[] args)
{
try {
Socket sock = new Socket("localhost", 8909);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out.println("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
out.println("Ut sem ante, mollis ut porttitor at, aliquet vel nulla.");
out.println("Suspendisse quis sapien ante, a cursus nunc.");
//---- sleep for 20 seconds -----
Thread.sleep(20000);
out.close();
in.close();
sock.close();
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
助けてくれてありがとう!