2012-04-11 83 views
1

我爲學校製作了這個程序,它涉及到一個telnet服務器。當我運行它時,它會返回奇怪的字符,如ÿûÿû。下面是輸出:Telnet服務器返回奇怪的字符

Client connected with the IP /127.0.0.1 
Client /127.0.0.1 has entered the username ÿûÿû ÿûÿû'ÿýÿûÿýdcole. 

我的代碼:

Socket client = serv.accept(); 

InetAddress clientip = client.getInetAddress(); 

out("Client connected with the IP " + clientip); 

InputStream clientinput = client.getInputStream(); 
OutputStream clientoutput = client.getOutputStream(); 

Scanner in = new Scanner(clientinput); 
clientoutput.write("Please enter your username: ".getBytes()); 

String username = in.nextLine(); 
out("Client " + clientip + " has entered the username " + username + "."); 

String pass = "Please enter the password for " + username + ": "; 
clientoutput.write(pass.getBytes()); 

String password = in.nextLine(); 

if (username.equals("dcole") && password.equals("test")) { 
    clientoutput.write("\r\nCorrect password!".getBytes()); 
} else { 
    clientoutput.write("\r\nIncorrect password!".getBytes()); 
} 

回答

2

也許有您創建的Socket當你InputStream有些髒的信息。在請求用戶名之前,您是否可以清除數據,例如撥打in.nextLine();並丟棄數據,或者致電clientinput.skip(clientinput.available());在詢問用戶名之前嘗試這樣做 - 即在創建Scanner之後立即執行此操作。

作爲一個後續內容,當您正在與Telnet服務器交談時,我肯定會鼓勵您遵循@StephenC的建議 - 您應該實現Telnet規範的正確握手和數據傳輸屬性,而不僅僅是通過Socket發送字符串。

+0

1.不,我用windows。 2.不,我只使用QWERTY鍵盤按鍵(英文)。 – cheese5505 2012-04-11 02:49:13

+0

此外,這不是作業:P – cheese5505 2012-04-11 02:53:13

+0

如何在我上面編輯的答案中嘗試點3 - 也許從創建時流是髒。 – wattostudios 2012-04-11 02:58:24

3

真正的問題在於,您將一個telnet服務器視爲一個簡單地發送和接收字符數據的套接字服務器。它沒有這樣的事情!

遠程登錄服務器按照RFC 854(更新爲支持Unicode RFC 5198)所述實現telnet協議。主RFC指定由telnet客戶端或服務器發送的一系列特殊序列。

如果您的客戶端能夠正常工作以抵禦任何telnet服務器,它需要正確實施協議。 WATTO建議的解決方法可能適用於這種情況......但您可能會發現這個(或另一個)telnet服務器會在其他位置插入這些「奇怪的字符」。事實上,他們根本不是「陌生人物」。它們是telnet協議中明確定義的元素,它們意味着什麼。

+0

我完全同意@StephenC - 它幾乎肯定是telnet協議的一部分,我似乎忽略了這個用戶試圖與遠程登錄服務器通信的事實。我的迴應確實是試圖「緩解」用戶遇到的問題,而不是像你的那樣更正確的答案。我不確定用戶試圖用他的Socket來做什麼,但我肯定會鼓勵正確實施telnet協議,而不是簡單地通過Socket發送Strings。 – wattostudios 2012-04-11 13:02:27