当您花费数小时追查不存在的问题时,您不讨厌它吗?在我尝试为 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);
}
}
}
谢谢您的帮助!