我转向你,我的头一直撞在墙上。
我正在做一个小的socket编程,当我把out.println(“…”)行代码放在while循环(in.readLine())之前时,可以看到它工作正常,但我需要它在循环中。
要说清楚,我没有看到任何错误。我只是没有看到文本出现在这个应用程序的客户端。它看起来好像在工作,但实际上不是。另外,我也不控制客户端,它由一个通过TCP连接到这个套接字侦听器应用程序的设备来处理。它是否有可能在读取数据后立即断开连接?
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");