如何让服务器在连接时向客户端发送消息?

发布于 2024-10-21 08:58:24 字数 789 浏览 1 评论 0原文

我正在尝试编写一个基本的客户端-服务器程序,以允许客户端遍历服务器的文件。我希望服务器在连接客户端时将当前目录中所有文件的列表发送给客户端。我该怎么做呢?我已经创建了所有文件名的数组,并尝试将它们发送到客户端,它只是处于无限循环中(正如它的意思!)并且什么也不做。

尝试让服务器在客户端连接上发送消息:

    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());


    boolean found = false;

    //Read the data from the input stream
    for (int i=0;i < fileList.length;i++) {
      outToClient.writeBytes(fileList[i].getName());
    }

并让服务器接收此消息:

//Prepare an object for reading from the input stream
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

//Read the data from the input stream
sentence = inFromServer.readLine();

但这样做只会使客户端陷入无限循环而不执行任何操作。

请帮忙?

I am trying to write a basic client-server program to allow the client to traverse the files of the server. I wish to get the server to, on connection of the client, send a list of all the files in the current directory to the client. How would I go about doing this ? I have already created an array of all the filenames, and am trying to send these to the client it just sits in an infinite loop (as it is meant to !) and does nothing.

Attempting to have the server send a message on connection of the client :

    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());


    boolean found = false;

    //Read the data from the input stream
    for (int i=0;i < fileList.length;i++) {
      outToClient.writeBytes(fileList[i].getName());
    }

And to have the server receive this :

//Prepare an object for reading from the input stream
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

//Read the data from the input stream
sentence = inFromServer.readLine();

but doing this just makes the client sit in an infinite loop and do nothing.

Help please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

绮烟 2024-10-28 08:58:24

您的主要问题是您尝试从客户端向服务器发送空字符串。空字符串转换为 0 长度字节数组。实际上,您没有在客户端和服务器之间发送任何数据。在这种情况下,您的服务器将继续等待通过套接字的 InputStream 检索数据。由于服务器仍在等待,因此它不会继续将数据发送回客户端。因此,当您的客户端尝试侦听来自服务器的数据时,它会无限期地等待,因为服务器永远不会到达该部分代码。

如果您的目标是让服务器在连接时简单地发送数据,那么您有几个选择。

  1. 连接后,服务器立即将列表发送给客户端。您不必在这里进行双向通信。客户端可以立即开始监听InputStream。
  2. 让客户端向服务器发送至少 1 个字节,服务器将能够通过其 InputStream 检索该字节,然后继续处理。如果您需要执行多个功能,那么您可能需要考虑发送一个有意义的字符串值,例如 out.write("list".getBytes("UTF-8"));然后,服务器可以根据接收到的值执行操作。

服务器示例:

ServerSocket socket = new ServerSocket(8888);
Socket cSocket = socket.accept();

PrintWriter out = null;
try {
    out = new PrintWriter(new OutputStreamWriter(cSocket.getOutputStream()));

    for (String file : new File(".").list()) {
        out.println(file);
    }
}
finally {
    if (out != null) {
        out.close();
    }
    cSocket.close();
    socket.close();
}

客户端示例:

Socket s = new Socket("localhost", 8888);
BufferedReader in = null;

try {
    in = new BufferedReader(new InputStreamReader(s.getInputStream()));

    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
}
finally {
    if (in != null) {
        in.close();
    }
    s.close();
}

You primary problem is that you are attempting to send an empty string from the client to the server. An empty string translates to a 0 length byte array. In effect, you are not sending any data between the client and the server. In this situation, your server will continue to wait for data to be retrieved over the socket's InputStream. Since the server is still waiting, it does not move on to send the data back to the client. As a result, when you client tries to listen for data from the server, it waits indefinitely as the server never reaches that part of the code.

If your goal is to have the server simply send the data upon connect, you have a couple of options.

  1. Upon connection have the server immediately send the list to the client. You do not have to have two way communication here. The client can start listening on the InputStream immediately.
  2. Have the client send at least 1 byte to the server that server will be able to retrieve over its InputStream and then continue to process. If you need to perform multiple functions, then you may want to look into sending a string value that means something, e.g., out.write("list".getBytes("UTF-8")); The server can then perform an operation based on the received value.

Example Server:

ServerSocket socket = new ServerSocket(8888);
Socket cSocket = socket.accept();

PrintWriter out = null;
try {
    out = new PrintWriter(new OutputStreamWriter(cSocket.getOutputStream()));

    for (String file : new File(".").list()) {
        out.println(file);
    }
}
finally {
    if (out != null) {
        out.close();
    }
    cSocket.close();
    socket.close();
}

Example Client:

Socket s = new Socket("localhost", 8888);
BufferedReader in = null;

try {
    in = new BufferedReader(new InputStreamReader(s.getInputStream()));

    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
}
finally {
    if (in != null) {
        in.close();
    }
    s.close();
}
貪欢 2024-10-28 08:58:24

首先确保客户端和服务器之间进行以下握手:

  1. 侦听服务器
  2. 客户端连接
  3. 服务器接受
    现在有两条路径:
  4. 服务器监听命令
  5. 客户端发送命令“dir”
  6. 客户端开始监听
  7. 服务器发回您的列表
    备用路径:
  8. 客户端侦听
  9. 服务器发送列表
  10. 服务器开始侦听

...正常通信。
发送 0 大小的消息有时可能会导致问题。
因此,使用查询响应方法似乎是准确的。

First make sure that you have following handshaking between client and server:

  1. listening server
  2. client connecting
  3. server accepts
    now there are two paths:
  4. server listen for command
  5. client sends command 'dir'
  6. client start to listen
  7. server sends back your list
    alternate path:
  8. client listens
  9. server sends list
  10. server start to listen

... normal communication.
Sending 0 size messages might cause problems sometimes.
So using query-response approach seems to be accurate.

一念一轮回 2024-10-28 08:58:24

在我的基本服务器-客户端 TCP 示例中,我提出了一种方法...当客户端被接受时,它会收到一条欢迎消息。当我从客户端发送角色时,它会返回名称。这是来源的链接>> http://matrixsust.blogspot.com/2011/10/basic -tcp-server-client.html

希望有帮助。

In my basic server-client TCP example I make a way ...when a client is got accepted it got a welcome message . In that when from client side I send role , it gives me back name. Here is the link of source >> http://matrixsust.blogspot.com/2011/10/basic-tcp-server-client.html .

Hope it helps.

抹茶夏天i‖ 2024-10-28 08:58:24

我不相信服务器可以在没有提示的情况下向客户端发送消息。发送消息“dir”并在服务器上监听,然后在客户端上监听并回复。

I don't believe it is possible to have a server send a message to a client unprompted. Send a message "dir" and listen on the server, then listen on client and reply.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文