java - 客户端和服务器之间的通信出现一些故障

标签 java sockets client

我这里有客户端和服务器端程序。客户端通过发送字符串与服务器对话,服务器然后将字符串转换为大写字母并发回。问题是客户端没有从服务器接收到任何字符串。只有服务器打印 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/

相关文章:

java - 绘制谢尔宾斯基三角形分形 - Java

c - 带有空 fd 集的套接字选择

python - 如何在 Python 中读取连续的 HTTP 流数据?

node.js - 使用原始node.js和cookie在客户端浏览器中存储 session ,而不使用express

java - 扩展 ImmutableCollection

java - 双倍流

java - 如何预测Java中的死锁

java - 将套接字连接绑定(bind)到不同机器上的不同端口?

java - 套接字——来自 python 和 java 的不同字节

c - 客户端的 read() 失败 C