所以服務(wù)器程序由以下代碼組成:import java.io. * ;import java.net. * ;import java.util. * ;public class TimeServer { public static void main(String[] args) { try { //Create sockets ServerSocket ss = new ServerSocket(60000); Socket rs = ss.accept(); //create streams BufferedInputStream bs = new BufferedInputStream(rs.getInputStream()); InputStreamReader isr = new InputStreamReader(bs); BufferedOutputStream bos = new BufferedOutputStream(rs.getOutputStream()); PrintWriter pw = new PrintWriter(bos); //set timeout rs.setSoTimeout(20000); int c = 0; StringBuilder sb = new StringBuilder(); //while loop reads in a character until a period (includes period) while (((char) c != '.')) { c = isr.read(); //append each char to a string builder sb.append((char) c); } //convert stringbuilder to string String str = sb.substring(0); //If string equals "time." returns time else error message if (str.compareTo("time.") == 0) { Date now = new Date(); pw.print("time is: " + now.toString()); pw.flush(); } else { pw.print("Invalid syntax: connection closed"); pw.flush(); } //close socket rs.close(); //close serversocket ss.close(); } catch(IOException i) { System.out.println(i.getMessage()); } }}問題是,如果我在單獨(dú)的 cmd.exe 中運(yùn)行每個(gè)程序,盡管使用 localhost 作為 IP 地址,它們?nèi)詿o法通信。我似乎無法在導(dǎo)致此問題的代碼中找到邏輯錯(cuò)誤,想知道是否有人可以提供幫助?
1 回答

慕慕森
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
問題是您正在使用 BufferedOutputStream,并且在 PrintWriter 上寫入后立即關(guān)閉套接字。您所寫的內(nèi)容保留在緩沖區(qū)中,并且套接字在任何內(nèi)容發(fā)送到客戶端之前關(guān)閉。
您需要flush在關(guān)閉之前以強(qiáng)制發(fā)送緩沖區(qū)的內(nèi)容:
...
//close socket
pw.flush();
rs.close();
...
TimeClient 包含一個(gè)小錯(cuò)誤:你循環(huán)接收直到你得到一個(gè)-1正確的,但是你將它附加-1到StringBuilder錯(cuò)誤的。它應(yīng)該是:
//while loop reads each character into stringbuilder
while(true){
c = isr.read();
if (c == -1) { break; }
sb.append((char) c);
}
但這永遠(yuǎn)不會(huì)阻止顯示文本......
添加回答
舉報(bào)
0/150
提交
取消