我求助于 StackOverflow,我一直在用头撞墙。
我正在做一些套接字编程,当我将 out.println("...") 代码行放在 while 循环(in.readLine())之前时,我可以看到它工作正常,但我需要它在循环内。
明确地说,我没有看到任何错误。我只是没有看到文本出现在此应用程序的客户端。它看起来好像在工作,但实际上没有。此外,我也不控制客户端,它由通过 TCP 连接到此 Socket Listener 应用程序的设备处理。有没有可能一读取数据就断开连接?
public class ConnectionHandlerTCP implements Runnable
{
private final Socket clientSocket;
ConnectionHandlerTCP(Socket socket)
{
clientSocket = socket;
}
public void run()
{
int uniqueId = 0;
try (
BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
){
String inputLine;
// This Line WORKS, I see it appear on the other side of the connection.
Log.debug("Sending now A");
out.println("text to send here");
while ((inputLine = in.readLine()) != null)
{
// This Line DOES NOT WORK, I do not see it on the other side of the connection.
//Log.debug("Sending now B");
//out.println("text to send here");
// ... bunch of commented out code here
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
Log.error("Exception caught when trying to read input.", e.getMessage());
} catch (Exception e) {
Log.error("Exception caught when trying to parse data.", e.getMessage());
}
}
}
如有任何帮助,我们将不胜感激。如果有帮助,这里是主类。
import java.net.*;
import java.io.*;
public class SocketListenerTCP
{
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
while(true)
{
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
) {
Socket clientSocket = serverSocket.accept();
new Thread(new ConnectionHandlerTCP(clientSocket)).start();
} catch (IOException e) {
Log.error("Exception caught", e.getMessage());
}
}
}
}
我稍微简化了一点,完全去掉了循环,但仍然无法正常工作。
inputLine = in.readLine();
Log.debug(inputLine);
Log.debug("Sending now");
out.println("text to send here");
最佳答案
里面的代码
while ((inputLine = in.readLine()) != null)
很可能没有运行,因为 in.readLine
一直在等待来自客户端的输入。
客户端程序/套接字需要有它在 PrintWriter
和 println
上,以便你的 while
循环可以读取它并响应(假设这就是您想要实现的目标)。
关于Java:无法在套接字 in.readLine() 之后写入套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53877025/