在 Sockets 和 ServerSockets 之间发送和接收信息
下面的代码应该从套接字接收时间,添加 6 个月的时间并将其返回到套接字。这是初始化套接字和服务器的代码:
//open and connect the sockets
ServerSocket ss = new ServerSocket(4444);
System.out.println("1");
Socket sock = new Socket(ss.getInetAddress(),4444);
System.out.println("2");
Socket srv = ss.accept();
System.out.println("3");
这是显示服务器接收时间并添加 6 个月的代码(时间格式为 YYYYMMDDHHMMSS)。
//send/receive and increment the current time by 6 months
PrintWriter bw = new PrintWriter(sock.getOutputStream());
System.out.println("4");
bw.print(rtime);
System.out.println("5");
//add 6 months to the current time
long ret = Long.valueOf(new BufferedReader(new InputStreamReader(srv.getInputStream())).readLine()) + 600000000;
System.out.println("6");
变量 rtime 是一个已经声明的long
。该代码位于 try{}
中,然后
catch(Exception e) {
System.out.println(e);
System.exit(-1);
}
我将打印行放入代码中以查看错误发生的位置,因为由于某种原因,程序终止而没有打印错误。所有数字都会被打印,直到“6”。换句话说,错误是在 .readline()
行遇到的。我不知道我做错了什么。非常感谢任何帮助,谢谢。
The following code is supposed to receive a time from a socket, add 6 months to the time and return it to the socket. Here is the code that initializes the sockets and servers:
//open and connect the sockets
ServerSocket ss = new ServerSocket(4444);
System.out.println("1");
Socket sock = new Socket(ss.getInetAddress(),4444);
System.out.println("2");
Socket srv = ss.accept();
System.out.println("3");
Here is the code that shows the server receiving the time and adding 6 months to it (format of the time is YYYYMMDDHHMMSS).
//send/receive and increment the current time by 6 months
PrintWriter bw = new PrintWriter(sock.getOutputStream());
System.out.println("4");
bw.print(rtime);
System.out.println("5");
//add 6 months to the current time
long ret = Long.valueOf(new BufferedReader(new InputStreamReader(srv.getInputStream())).readLine()) + 600000000;
System.out.println("6");
The variable rtime, is a long
that is already declared. The code is within a try{}
followed by
catch(Exception e) {
System.out.println(e);
System.exit(-1);
}
I put the printing lines in the code to see where the error takes place, since for some reason, the program terminates without printing an error. All numbers get printed, until "6". In other words the error is met at the .readline()
line. I don't know what I am doing wrong. Any help is much appreciated, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加
bw.flush()
之后
请在
bw.print(rtime);
;这是刷新客户端套接字输出流中的内容所必需的,该内容随后可在服务器套接字。
否则,在您的示例中 readline();不会出来,因为它是一个阻塞调用。
Please add
bw.flush();
after
bw.print(rtime);
This is required to flush the contents from client sockets output stream which would then be available at input of server socket.
Otherwise, in your example readline(); would not come out as it is a blocking call.