java 使用java向特定客户端发送消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36849197/
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
send message to specific clients using java
提问by zeeshan nisar
How can i send message from server to any specific client. I have the concept of how to do it like i have to make a list of all the clients connected to server and then by iterating each client i can send message but i will be thankful if any one can help me by code.I have searched many codes but i didn't get any considerable help from them Code shouldn't be GUI based. Thanks in advance.Sorry for my bad English. This is my code in which message is send to all clients but i want to send message to a client of my choice using clients ipaddress
如何从服务器向任何特定客户端发送消息。我有如何做到这一点的概念,就像我必须列出连接到服务器的所有客户端,然后通过迭代每个客户端我可以发送消息,但如果有人可以通过代码帮助我,我将不胜感激。我已经搜索过许多代码,但我没有从他们那里得到任何相当大的帮助代码不应该基于 GUI。提前致谢。抱歉我的英语不好。这是我的代码,其中将消息发送到所有客户端,但我想使用客户端 ipaddress 将消息发送到我选择的客户端
Map<Integer, java.net.Socket> clients = new HashMap<Integer, java.net.Socket> ();
socket = serverSocket.accept();
// Add the socket to a HashMap
clients.put(socket.getPort(), socket);
for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); )
{
int key = iter.next();
java.net.Socket client = clients.get(key);
// Sending the response back to the client.
// Note: Ideally you want all these in a try/catch/finally block
OutputStream os = client.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Some message");
bw.flush();
}
回答by Michael Markidis
What I would do is create a Client class:
我要做的是创建一个 Client 类:
class Client
{
private String userName;
private String ipAddress;
private java.net.Socket socket = null;
public Client (String userName, String ipAddress, java.net.Socket socket)
{
this.userName = userName;
this.ipAddress = ipAddress;
this.socket = socket;
}
public java.net.Socket getSocket()
{
return this.socket;
}
}
Instead of adding just the socket and port number to the map, I would map the combination of the userName and ipAddres to a Client object.
我不是只将套接字和端口号添加到映射中,而是将 userName 和 ipAddres 的组合映射到 Client 对象。
socket = serverSocket.accept();
// get the username from the socket
// get the ipAddress from the socket
Client c = new Client(userName, ipAddress, socket);
// Add the client to a HashMap
clients.put(userName + ":" + ipAddress, c);
Now, you can send a message to a specific client based on the username and ipAddress:
现在,您可以根据用户名和 ipAddress 向特定客户端发送消息:
public void sendToOneClient (String userName, String ipAddress, Map<String, Client> clients)
{
Client c = clients.get(userName + ":" + ipAddress);
java.net.Socket socket = c.getSocket();
// Sending the response back to the client.
// Note: Ideally you want all these in a try/catch/finally block
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Some message");
bw.flush();
}
回答by sockpuppetcow
I'd use Socket.getInetAddress()and compare the result to whatever you have the IPs you want to send to in. Personally, I'd use a String[]
or ArrayList<String>
for that. Here's an example:
我会使用Socket.getInetAddress()并将结果与您想要发送的任何 IP 进行比较。就个人而言,我会使用 aString[]
或ArrayList<String>
。下面是一个例子:
ArrayList<String> addresses;
//TODO: Add things to 'addresses'
clients.put(socket.getPort(), socket);
for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); )
{
int key = iter.next();
java.net.Socket client = clients.get(key);
//Checking to make sure it's a client we want to send to.
if (addresses.contains(client.getInetAddress().toString()) {
// Sending the response back to the client.
// Note: Ideally you want all these in a try/catch/finally block
OutputStream os = client.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Some message");
bw.flush();
}
}
Alternatively, you could store the sockets in your HashMap by the InetAddress instead.
或者,您可以通过 InetAddress 将套接字存储在您的 HashMap 中。
回答by ControlAltDel
You can store a relationship between how you want to look up the client with the socket that they are on. The natural way to do this is with a map, like
您可以存储您希望如何使用客户端所在的套接字查找客户端之间的关系。这样做的自然方法是使用地图,例如
Map<String, Socket> sockets = new HashMap<String,Socket>();
...
ServerSocket ss = ...;
Socket s = ss.accept();
String username = getUserName(s);
sockets.put(username, s);
Obviously, in this example here, the client would have to send his/her userName in a format which you expect to receive after making the Socket connection
显然,在此示例中,客户端必须以您希望在建立 Socket 连接后接收的格式发送他/她的用户名
回答by joe pelletier
I have found that it is effective to create an object type that can hold both a unique name or id be it an int
or a String
and also a Socket
. You could store instances of this object in an ArrayList
(or any other list) and iterate through them searching for the name or id that you want to use.
我发现创建一个对象类型是有效的,它可以同时包含一个唯一的名称或 id,可以是 anint
或 aString
也可以是Socket
. 您可以将此对象的实例存储在ArrayList
(或任何其他列表)中,并遍历它们以搜索您要使用的名称或 ID。
回答by Sandun
This is what I did for my program.Here I used the ">>" string to specify that a message should be sent to a particular user. (e.g.: "Ross>>Hi Ross What's Up?" means that the message should be sent to the user named 'Ross'). I used a HashMap(named 'WritersMap') to keep details as KEY-VALUE pairs. Key will be the name of the user who sends the particular message and Value will be that message. 'in' is a BufferedReader instance.
这就是我为我的程序所做的。这里我使用“>>”字符串来指定应该向特定用户发送消息。(例如:"Ross>>Hi Ross What's Up?" 表示该消息应该发送给名为'Ross' 的用户)。我使用 HashMap(名为“WritersMap”)将详细信息保存为 KEY-VALUE 对。Key 将是发送特定消息的用户的名称,Value 将是该消息。'in' 是一个 BufferedReader 实例。
while (true) {
String input = in.readLine();
if (input == null) //if there is no input,do nothing
{
return;
}
//when a user sends a message to a specific user
else if(input.contains(">>")) //checks whether the message contains a >>
{
String person=input.substring(0,input.indexOf(">")); //extract the name of the destination user
for(HashMap.Entry<String,PrintWriter> entry:writersMap.entrySet()) //find the destination user from the users list
{
if(entry.getKey().matches(person)) //if the destination user is found
{
PrintWriter writer=entry.getValue();
writer.println("MESSAGE " + name + ": " + input);
}
}
}
else //when a user sends a broadcast message to all users
{
for(HashMap.Entry<String,PrintWriter> entry:writersMap.entrySet()) //find the destination user from the users list
{
PrintWriter writer=entry.getValue();
writer.println("MESSAGE " + name + ": " + input);
}
}
}