我有一个多聊天服务器客户端程序,我正在尝试在 telnet putty 窗口中从客户端获取输入。 提示:
String login = "2-Enter Username and a password:";
clientoutput.write((login).getBytes());
这是由 BufferedReader 读取的:
BufferedReader br = new BufferedReader(new InputStreamReader(clientInput));
String inputLine;
String returnMessage;
while ((inputLine = br.readLine()) != null) {
// Split input line with space as delimiter using import jar
String[] words = StringUtils.split(inputLine);
// Ensure we don't get a null pointer
if (words != null && words.length > 0) {
String command = words[0];
if ("logoff".equalsIgnoreCase(command) || "q".equalsIgnoreCase(command) || "quit".equalsIgnoreCase(command)) {
logOff();
break;
}else
// Log user in
try {
clientLogIn(clientoutput, words);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
但是,用户输入的第一个单词始终读作
ÿû
: Eclipse 控制台输出:
User ÿû has logged in
所以我的问题是这个角色ÿû来自哪里,有解决办法吗?
我使用的是 WIndows 10 和 Eclipse 版本:2019-03 (4.11.0) 版本号:20190314-1200
附加信息: 我 try catch 用户输入并直接打印到控制台:
if (login.contains("ÿû")) {
login = login.substring(1);
System.out.println("New login after removal of unxepected char: " + login);
} else {
System.out.println("User eneterd login : " + login);
}
输出:
User entered login : -Enter Username and a password:
User ÿû has logged in // after the first word has been taken
最佳答案
由于您实际上是在编写自己的协议(protocol),因此问题似乎是您使用了错误的客户端来测试您的服务器。
也就是说,telnet 并不意味着作为一般的 TCP 客户端,因为它会在您尝试发送的实际数据旁边发送命令。另外,它适用于字节,而不是 java 字符串(当您尝试检查字符串开头的那些奇怪字符时您会注意到这一点)。
如果您使用 netcat
之类的东西来测试代码,则可以完全避免该问题。
关于java - 缓冲读取器从用户输入返回意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58875207/