所以目前我的ServerSocket看起来像这样
public class Main {
public static void main(String[] args) {
Server server = new Server(9008);
}
}
public class Server {
private ServerSocket server;
private Socket client;
private ArrayList<ClientConnection> clientList;
public Server(int port) {
try {
// Create out server with our desired port
server = new ServerSocket(port);
// Server started, let the user know
System.out.println("Server started at port " + port + "...");
} catch (IOException e) {
// Unable to start server, print error
System.out.println("Unable to start server on port " + port + "...");
}
// Start our main server method
runServer();
}
public void runServer() {
clientList = new ArrayList<>();
while (true) {
try {
// Wait for new clients and accept them
client = server.accept();
// Let the user know - print
System.out.println("New user connected - " + client.getLocalAddress().getHostAddress());
// Start thread for our client
ClientConnection getClient = new ClientConnection(client);
clientList.add(getClient);
Thread clientThread = new Thread(getClient);
clientThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ClientConnection implements Runnable {
private Socket socket;
public ClientConnection(Socket client) {
// Set client socket
this.socket = client;
}
public void run() {
try {
// Read from our client input
BufferedReader readClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = readClient.readLine()) != null) {
// Print client message
System.out.println("Client says - " + line);
}
} catch(IOException e) {
}
}
}
一切正常,客户端连接,发送一些数据和服务器读取它,但我的问题是 如何从我的服务器向所有客户端发送消息?我当前在ArrayList上保存客户端,所以我可以循环该ArrayList打开一个编写器并刷新它但我想发送我在ClientConnection类上获得的数据
我该如何处理这段代码?在服务器类上完成的一切?或..?
答案 0 :(得分:0)
不要太具体,但你应该环顾观察者模式。
当新客户端连接到服务器并创建ClientConnection
实例时,它可以被另一个处理消息的类观察和观察。这样,当客户端发送消息并且ClientConnection
处理它时,它会自动将其传输到处理消息传递功能的类并且知道所有连接,然后此类将消息传输给所有客户端。
Server
实现Observer接口,以便它可以观察到observable。ClientConnection
并让Server
收听它(addObserver()
)ClientConnection
执行setChanged()
和notifyObservers
Server
就会发现新消息的注意事项(通过update
方法应该实现)以及ClientConnection
发送的消息。Server
现在遍历其所有客户端并将消息发送给每个客户端请参阅Observer和Observable,这应该足够了。如果没有,那么有很多关于网络上观察者模式的文章。