TCP程序中的问题(Java)
谁能帮我调试这个程序吗?
以下是服务器代码:
package networking;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
while (true) {
Socket client = serverSocket.accept();
Scanner reader = new Scanner(client.getInputStream());
PrintWriter writer = new PrintWriter(client.getOutputStream());
String inputString = reader.nextLine();
System.out.println("Received from client : " + inputString);
writer.write(inputString.toUpperCase());
client.close();
}
}
}
这是客户端代码:
package networking;
import java.io.PrintWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
class TcpClient {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost", 5555);
PrintWriter writer = new PrintWriter(client.getOutputStream());
Scanner reader=new Scanner(client.getInputStream());
writer.println("oPen SOurCe RUleS !");
System.out.println("Received from server : "+reader.nextLine());
client.close();
}
}
问题是,当我运行该程序时,客户端和客户端都在运行。服务器进入无限期等待状态。有人能告诉我这段代码有什么问题吗?
提前致谢!
Can anyone help me debug this program?
The following is server code :
package networking;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
while (true) {
Socket client = serverSocket.accept();
Scanner reader = new Scanner(client.getInputStream());
PrintWriter writer = new PrintWriter(client.getOutputStream());
String inputString = reader.nextLine();
System.out.println("Received from client : " + inputString);
writer.write(inputString.toUpperCase());
client.close();
}
}
}
And this is the client code :
package networking;
import java.io.PrintWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
class TcpClient {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost", 5555);
PrintWriter writer = new PrintWriter(client.getOutputStream());
Scanner reader=new Scanner(client.getInputStream());
writer.println("oPen SOurCe RUleS !");
System.out.println("Received from server : "+reader.nextLine());
client.close();
}
}
The problem is that when I run this program both client & server go into indefinite waiting state.Could anyone tell me what's wrong with this code?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过 冲洗
PrintWriter
?您关闭了流,但您从未通知作者您将要这样做。
Have you tried Flushing the
PrintWriter
?You close the stream but you never notify the writer that you're about to do so.