gpt4 book ai didi

java - 向所有客户端发送消息(客户端 - 服务器通信)

转载 作者:太空狗 更新时间:2023-10-29 22:44:55 26 4
gpt4 key购买 nike

所以现在,我正在制作一个基于多线程的客户端服务器应用程序。在服务器端,我为接受的每个连接创建一个线程。

在线程类中,我创建了一个向客户端发送命令的方法。我只想要的是,如何向所有正在运行的客户端发送参数?对于简单的声明,我只是想让这个服务器向所有连接的客户端发送消息。

我已经读过this post并从 this link 中找到 sendToAll(String message) 方法.但是当我在我的代码中尝试时, ServerSocket 中没有这样的方法。

好的,这是我的服务器和线程示例代码。

class ServerOne{

ServerSocket server = null;
...

ServerOne(int port){
System.out.println("Starting server on port "+port);
try{
server = new ServerSocket(port);
System.out.println("Server started successfully and now waiting for client");

} catch (IOException e) {
System.out.println("Could not listen on port "+port);
System.exit(-1);
}
}

public void listenSocket(){
while(true){
ClientWorker w;
try{
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}

protected void finalize(){
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
}

class ClientWorker implements Runnable{
Socket client;

ClientWorker(Socket client){
this.client = client;
}
public void run(){
...
sendCommand(parameter);
...
}

public void sendCommand(String command){
PrintWriter out = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
out.println(command);
} catch (IOException ex) {}
}

}

感谢您的帮助:)

最佳答案

The below answer, is not recommended for a full fledged server, as for this you should use Java EE with servlets, web services etc.

This is only intended where a few computers want to connect to perform a specific task, and using simple Java sockets is not a general problem. Think of distributed computing or multi-player gaming.

编辑:自第一篇文章以来,我已经大大更新了这个架构,现在已经过测试并且是线程安全的。有需要的可以下载here .

只需使用(直接或子类化)ServerClientstart()它们,一切就绪。阅读内联评论以获得更强大的选项。


虽然客户端之间的通信相当复杂,但我会尽量简化它。

以下是服务器中的点:

  • 保留已连接客户端的列表。
  • 定义一个线程,用于服务器输入。
  • 定义接收消息的队列。
  • 从队列中轮询并使用它的线程。
  • 发送消息的一些实用方法。

对于客户:

  • 定义一个线程,用于客户端输入。
  • 定义接收消息的队列。
  • 从队列中轮询并使用它的线程。

这是服务器类:

public class Server {
private ArrayList<ConnectionToClient> clientList;
private LinkedBlockingQueue<Object> messages;
private ServerSocket serverSocket;

public Server(int port) {
clientList = new ArrayList<ConnectionToClient>();
messages = new LinkedBlockingQueue<Object>();
serverSocket = new ServerSocket(port);

Thread accept = new Thread() {
public void run(){
while(true){
try{
Socket s = serverSocket.accept();
clientList.add(new ConnectionToClient(s));
}
catch(IOException e){ e.printStackTrace(); }
}
}
};

accept.setDaemon(true);
accept.start();

Thread messageHandling = new Thread() {
public void run(){
while(true){
try{
Object message = messages.take();
// Do some handling here...
System.out.println("Message Received: " + message);
}
catch(InterruptedException e){ }
}
}
};

messageHandling.setDaemon(true);
messageHandling.start();
}

private class ConnectionToClient {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;

ConnectionToClient(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());

Thread read = new Thread(){
public void run(){
while(true){
try{
Object obj = in.readObject();
messages.put(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}
};

read.setDaemon(true); // terminate when main ends
read.start();
}

public void write(Object obj) {
try{
out.writeObject(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}

public void sendToOne(int index, Object message)throws IndexOutOfBoundsException {
clientList.get(index).write(message);
}

public void sendToAll(Object message){
for(ConnectionToClient client : clientList)
client.write(message);
}

}

这里是 Client 类:

public class Client {
private ConnectionToServer server;
private LinkedBlockingQueue<Object> messages;
private Socket socket;

public Client(String IPAddress, int port) throws IOException{
socket = new Socket(IPAddress, port);
messages = new LinkedBlokingQueue<Object>();
server = new ConnecionToServer(socket);

Thread messageHandling = new Thread() {
public void run(){
while(true){
try{
Object message = messages.take();
// Do some handling here...
System.out.println("Message Received: " + message);
}
catch(InterruptedException e){ }
}
}
};

messageHandling.setDaemon(true);
messageHandling.start();
}

private class ConnectionToServer {
ObjectInputStream in;
ObjectOutputStream out;
Socket socket;

ConnectionToServer(Socket socket) throws IOException {
this.socket = socket;
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());

Thread read = new Thread(){
public void run(){
while(true){
try{
Object obj = in.readObject();
messages.put(obj);
}
catch(IOException e){ e.printStackTrace(); }
}
}
};

read.setDaemon(true);
read.start();
}

private void write(Object obj) {
try{
out.writeObject(obj);
}
catch(IOException e){ e.printStackTrace(); }
}


}

public void send(Object obj) {
server.write(obj);
}
}

关于java - 向所有客户端发送消息(客户端 - 服务器通信),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13115784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com