gpt4 book ai didi

java - 我的服务器程序无法向我编写的客户端程序发送数据

转载 作者:行者123 更新时间:2023-12-02 09:42:25 25 4
gpt4 key购买 nike

所以服务器程序由以下代码组成:

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());
}
}
}

客户端的代码是:

import java.io. * ;
import java.net. * ;
import java.util. * ;

public class TimeClient {

public static void main(String[] args) {

try {
//create socket
Socket sock = new Socket("localhost", 60000);
//create streams
BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
InputStreamReader isr = new InputStreamReader(bis);
BufferedOutputStream bos = new BufferedOutputStream(sock.getOutputStream());
PrintWriter pw = new PrintWriter(bos);
//set timeout
sock.setSoTimeout(20000);
//write argument to stream, argument should be "time." to recieve time
pw.write(args[0]);
pw.flush();
int c = 0;
StringBuilder sb = new StringBuilder();
//while loop reads each character into stringbuilder
while ((c != -1)) {
c = isr.read();
sb.append((char) c);
}
//stringbuilder converted to string and printed
String str = sb.substring(0);
System.out.println(str);
//socket closed
sock.close();
} catch(IOException i) {
System.out.println(i.getMessage());
}
}
}

问题是,如果我在单独的 cmd.exe 中运行每个程序,尽管使用 localhost 作为 IP 地址,它们也不会进行通信。我似乎无法在代码中找到导致此问题的逻辑错误,并想知道是否有人可以提供帮助?

最佳答案

问题是您正在使用 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);
}

但这永远不会阻止文本的显示...

关于java - 我的服务器程序无法向我编写的客户端程序发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com