我遇到了一个非常奇怪的问题,过去两天让我很沮丧。我试过在这里寻找类似的问题,但没有找到解决方案。
我正在使用套接字从远程telnet会话记录器读取Java文件 我为输入和输出流定义了一个BufferedWriter和Reader,并将每个readLine刷新到一个文件。登录时我得到一个字符串,使用outputStream插入密码,然后开始在循环中读取插件。这在Windows上完美运行,没有任何问题。
现在,我尝试在Mac OS X(Yosemite)上运行相同的代码。我得到第一行(请求我插入密码),通过调试我注意到我也在写BufferedWriter的密码。但是,由于一些奇怪的原因,在下一个readLine迭代中,代码挂起,而不是获取日志输出,卡在下一个readLine实例上。如果它为null,则应该退出循环。我已经检查过在mac上手动打开一个telnet会话(使用secureCRT),并使用密码在O.K上工作。在插入一个错误的密码时,我也应该得到一行(“密码不正确”。但是在下一个readLine上我什么都没得到,它只是卡住了。
这是我的代码,有没有人知道我在这里做错了什么?它应该在MAC上以不同的方式工作吗?这真的会救我。谢谢!
这个片段是一个线程的一部分,但它与问题无关(或者我认为)。实际文件本身是在线程外部创建的。
public void run(){
String line = "-1";
try {
socket = new Socket(JSONReader.getPropertyByName("files/properties.json", "LOGGER_DNS_NAME"), 5550);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
instream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((line = instream.readLine()) != null) {
// Insert Username and Password in the Telnet session
line = instream.readLine();
if(line.startsWith("Please")){
bw.write("password");
bw.newLine();
bw.flush();
}
if (line.startsWith("Press")) {
System.out.println("Reached log");
bw.write("d");
bw.newLine();
bw.flush();
}
if (Thread.interrupted()){
try {
instream.close();
bw.close();
socket.close();
return;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not close socket");
System.exit(-1);
}
}
}
// Write the output to the log file
logfile.println(line);
logfile.flush();
} catch (UnknownHostException e) {
System.out.println("Could not open Telnet session to the server");
System.exit(1);
} catch (IOException e) {
System.out.println("There was a problem with file creation, or I/O exception");
System.exit(1);
}
}
答案 0 :(得分:1)
所以最后,在两种情况下嗅探服务器的tcp会话后,我发现了我的问题。
问题是BufferedWriter在使用write方法时,新行和flush,会自动生成行结尾(\ n)。除了在基于Linux的Mac OS上,行结尾应该是(\ r \ n)。
所以,不要使用"写"方法和"换行",我只是使用"追加"插入\ r \ n字符串相反(追加("密码\ r \ n))。