简体   繁体   中英

How do I send data to specific Socket connections?

I understood that every client is connected through a socket with a new thread each, but how do I send data to a specific client socket? What should I do to fix this issue? Here is my server's source code:

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);
        }    
    }
}

You can save all the users that are connecting to the server in a linked list and pass that as well to each client connection. That way you can traverse through the linked list to find the connection you want to communicate with and send data to its outputstream .

EDIT Example-

Code for server:

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);
        }
    }
    }
}

The server maintains a list of connected users in the List<ClientThread> users variable which can be accessed by the client threads.

ClientThread Code:

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
        }
    }
}
}

Set a name of the thread using this.setName() method. Should be a unique identifier.
Now you can communicate with the thread you want to using users variable and traversing through all of them using getName() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM