所以服务器程序由以下代码组成: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()); } }}问题是,如果我在单独的 cmd.exe 中运行每个程序,尽管使用 localhost 作为 IP 地址,它们仍无法通信。我似乎无法在导致此问题的代码中找到逻辑错误,想知道是否有人可以提供帮助?
1 回答
慕慕森
TA贡献1856条经验 获得超17个赞
问题是您正在使用 BufferedOutputStream,并且在 PrintWriter 上写入后立即关闭套接字。您所写的内容保留在缓冲区中,并且套接字在任何内容发送到客户端之前关闭。
您需要flush在关闭之前以强制发送缓冲区的内容:
...
//close socket
pw.flush();
rs.close();
...
TimeClient 包含一个小错误:你循环接收直到你得到一个-1正确的,但是你将它附加-1到StringBuilder错误的。它应该是:
//while loop reads each character into stringbuilder
while(true){
c = isr.read();
if (c == -1) { break; }
sb.append((char) c);
}
但这永远不会阻止显示文本......
添加回答
举报
0/150
提交
取消