[英]how to listen to one client at a time in java using server socket?
import java.io.*;
import java.net.*;
class MultiServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSock=new ServerSocket(3000);
//server socket creation
System.out.println("waiting for client.........");
Socket socket=serverSock.accept();
System.out.println("client connected ");
BufferedReader keyRead=new BufferedReader(new
inputStreamReader(System.in));
OutputStream ostream=socket.getOutputStream();//sending to client
PrintWriter pw=new PrintWriter(ostream,true);
InputStream istream=socket.getInputStream();//receiving from
server(istream objehect)
BufferedReader receiveRead=new BufferedReader(new
InputStreamReader(istream));
String receiveMessage,sendMessage;
while(true)
{
if((receiveMessage=receiveRead.readLine())!= null)
{
System.out.println("client:>"+ receiveMessage);
}
sendMessage=keyRead.readLine();
pw.println(sendMessage);
System.out.flush();//flush the Stream
if(sendMessage.equals("bye"))
{
break;
}
}
}
}
this code is to connect a client at a time , but i want to display a message that the server is busy if other client attempts to chat with the same server. 这段代码是一次连接一个客户端,但是如果其他客户端尝试与同一服务器聊天,我想显示一条消息,表明服务器正忙。 that message should respond on both the side.
该消息应该在双方都响应。
i want to display a message that the server is busy if other client attempts to chat with the same server.
如果其他客户端尝试与同一服务器聊天,我想显示一条消息,表明服务器正忙。 that message should respond on both the side
该消息应该在双方都响应
Basically impossible. 基本上是不可能的。 The
listen()
backlog queue will cause a subsequent client's connection attempt to complete and be queued for the next accept()
call by the server. listen()
待办事项队列将导致后续客户端的连接尝试完成,并排队等待服务器进行下一个accept()
调用。 There is nothing you can do about this short of closing the listening socket until you're ready to accept the next client, which introduces all kinds of timing constraints. 在准备好接受下一个客户端之前,关闭监听套接字是无能为力的,它引入了各种时序约束。
You could set a flag while you have a client and check it when you accept another one, and send him the message and disconnect him, but I fail to see the point. 您可以在有客户的时候设置一个标志,并在接受另一个客户时对其进行检查,然后向他发送消息并断开他的连接,但是我看不出重点。
that message should respond on both sides
该消息应该在双方都回应
What both sides? 双方是什么? The side of the new client and who else?
新客户方面,还有谁呢?
Strange requirement. 奇怪的要求。 How can a chat server only want one client?
聊天服务器如何只需要一个客户端? Who is he chatting to?
他在跟谁聊天?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.