java 如何让服务器在连接时向客户端发送消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5260624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a server to send a client a message on connection?
提问by John McCarthy
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?
请帮忙?
采纳答案by Kris Babic
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.
您的主要问题是您试图从客户端向服务器发送一个空字符串。空字符串转换为长度为 0 的字节数组。实际上,您没有在客户端和服务器之间发送任何数据。在这种情况下,您的服务器将继续等待通过套接字的 InputStream 检索数据。由于服务器仍在等待,它不会继续将数据发送回客户端。因此,当您的客户端尝试从服务器侦听数据时,它会无限期地等待,因为服务器永远不会到达该部分代码。
If your goal is to have the server simply send the data upon connect, you have a couple of options.
如果您的目标是让服务器在连接时简单地发送数据,您有几种选择。
- 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.
- 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.
- 连接后,服务器立即将列表发送给客户端。您不必在这里进行双向通信。客户端可以立即开始侦听 InputStream。
- 让客户端向服务器发送至少 1 个字节,服务器将能够通过其 InputStream 检索,然后继续处理。如果您需要执行多个功能,那么您可能需要考虑发送一个有含义的字符串值,例如 out.write("list".getBytes("UTF-8")); 然后服务器可以基于接收到的值执行操作。
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();
}
回答by bua
First make sure that you have following handshaking between client and server:
首先确保您在客户端和服务器之间进行了以下握手:
- listening server
- client connecting
- server accepts
now there are two paths: - server listen for command
- client sends command 'dir'
- client start to listen
- server sends back your list
alternate path: - client listens
- server sends list
- server start to listen
- 监听服务器
- 客户端连接
- 服务器
现在接受有两条路径: - 服务器监听命令
- 客户端发送命令“dir”
- 客户开始聆听
- 服务器发回您的列表
备用路径: - 客户倾听
- 服务器发送列表
- 服务器开始监听
... normal communication.
Sending 0 size messages might cause problems sometimes.
So using query-response approach seems to be accurate.
... 正常交流。
发送 0 大小的消息有时可能会导致问题。
所以使用查询-响应方法似乎是准确的。
回答by Robel Sharma
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.
在我的基本服务器-客户端 TCP 示例中,我做了一个方法......当客户端被接受时,它会收到一条欢迎消息。当我从客户端发送 role 时,它给了我名字。这是源的链接>> http://matrixsust.blogspot.com/2011/10/basic-tcp-server-client.html。
Hope it helps.
希望能帮助到你。
回答by John McCarthy
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.
我不相信有可能让服务器在不提示的情况下向客户端发送消息。发送消息“dir”并在服务器上侦听,然后在客户端侦听并回复。