我知道每个客户端都是通过套接字连接的,每个客户端都有一个新线程,但是如何将数据发送到特定的客户端套接字?我该怎么做才能解决这个问题?这是我服务器的源代码:
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
public Server() throws IOException {
ServerSocket ss = new ServerSocket(1124);
ExecutorService executorService = Executors.newFixedThreadPool(100);
System.out.println("Server is running");
while (true) {
Socket s = ss.accept();
executorService.execute(new ConnectionHandler(s));
}
}
public static void main(String[] args) throws IOException {
new Server();
}
}
class ConnectionHandler implements Runnable {
Socket s;
public ConnectionHandler(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
} catch (IOException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
答案 0 :(得分:0)
您可以在链接列表中保存连接到服务器的所有用户,并将其传递给每个客户端连接。这样,您可以遍历链接列表以查找要与之通信的连接,并将数据发送到outputstream
。
编辑示例 -
服务器代码:
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.LinkedList;
import java.util.List;
public class DBServer {
static boolean listening = true;
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
static List<ClientThread> users = null;
public static void main(String[] args) {
users= new LinkedList();
int portNumber = 17000;
System.out.println("Now using port number=" + portNumber);
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
while (listening) {
try {
System.out.println("Number of users connected: " + users.size());
clientSocket = serverSocket.accept();
System.out.println("Someone just joined.");
ClientThread ct= new ClientThread(clientSocket);
users.add(ct);
ct.start();
}catch (IOException e) {
System.out.println(e);
}
}
}
}
服务器维护List<ClientThread> users
变量中的连接用户列表,客户端线程可以访问该列表。
ClientThread代码:
public class ClientThread implements Runnable {
private Socket clientSocket = null;
ClientThread(Socket s){
this.clientSocket= s;
//give this thead a unique identifier like a name using this.setName() method
}
void sendMessage(){
for (ClientThread c : DBServer.users) {
if(c.getName().equals(/*Name of thread you want to contact*/)){
//send message here
}
}
}
}
使用this.setName()
方法设置线程的名称。应该是唯一的标识符
现在,您可以使用users
变量与要使用getName()
变量遍历所有变量的线程进行通信。