我这里有客户端和服务器端程序。客户端通过发送字符串与服务器对话,服务器然后将字符串转换为大写字母并发回。问题是客户端没有从服务器接收到任何字符串。只有服务器打印 2 传入的字符串,然后服务器抛出 IOException。我猜这是因为客户端关闭了连接。但是为什么客户端收不到服务器的消息呢?如何克服这个问题? 谢谢
Client:
package solutions;
import java.io.*;
import java.net.*;
class SocketExampleClient {
public static void main(String [] args) throws Exception {
String host = "localhost"; // hostname of server
int port = 5678; // port of server
Socket s = new Socket(host, port);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("Hello World!");
System.out.println(dis.readUTF());
dos.writeUTF("Happy new year!");
System.out.println(dis.readUTF());
dos.writeUTF("What's the problem?!");
System.out.println(dis.readUTF());
}
}
服务器:
package solutions;
import java.io.*;
import java.net.*;
class SocketExampleServer {
public static void main(String [] args) throws Exception {
int port = 5678;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting incoming connection...");
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
String x = null;
try {
while ((x = dis.readUTF()) != null) {
System.out.println(x);
dos.writeUTF(x.toUpperCase());
}
}
catch(IOException e) {
System.err.println("Client closed its connection.");
}
}
}
输出:
Waiting incoming connection...
Hello World!
Happy new year!
What's the problem?!
Client closed its connection.
最佳答案
您的主程序在有机会读取服务器响应之前就退出了。如果添加以下代码,它将正常工作。 :) 更新-我刚刚意识到你的代码在我的计算机上运行良好-并且它确实按预期输出了字符串。 DataInputStream.readUTF() 正确阻塞并接收响应。您还有问题吗?
Thread t = new Thread(){
public void run()
{
for(;;)
{
String s = null;
try
{
s = dis.readUTF();
}
catch (IOException e)
{
e.printStackTrace();
}
while(s!=null)
{
System.out.println("Output: " + s);
try
{
s = dis.readUTF();
}
catch (IOException e)
{
e.printStackTrace();
}
}}}};
t.start();
关于java - 客户端和服务器之间的通信出现一些故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9546599/