我已经创建了插座,只是如何打印到所有插座Java服务器?(I've created a Ja

2019-07-31 19:44发布

我一直想这一段时间,我想多个客户端同时收到多个输入。
有一个问题,我希望服务器打印“嗨”到所有客户端,如果一个客户说“嗨print2all”。
我知道如何处理它打印出来,只是打印到所有客户端的问题。

这是我到目前为止所。
服务器

try{
    try{
        server = new ServerSocket(25565);
    } catch (Exception e){
        e.printStackTrace();
    }
    while (isListening){
        new SocketThread(server.accept()).start();
    }
    server.close();
} catch (Exception e){
    e.printStackTrace();
}

SocketThread

try {
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String inputLine, outputLine;
    Processor kkp = new Processor();
    out.println("Hi!");

    while ((inputLine = in.readLine()) != null) {
        outputLine = kkp.Proccess(inputLine,this.socket);
        out.println(outputLine);
    }
    out.close();
    in.close();
    socket.close();

} catch (IOException e) {
    e.printStackTrace();
}

客户

            Processor p = new Processor();
            socket = new Socket("localhost",25565);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
            out.println("print2all Hi")            
            socket.close();

Answer 1:

首先,你需要保持所有连接的客户端跟踪:

final List<SocketThread> clients = new ArrayList<>();

while (isListening){
    SocketThread client = new SocketThread(server.accept()).start();
    clients.add(client);
}

有了这样列表中,如果一个客户端收到"print2all Hi"它简单地对所有遍历clients并发送消息给他们每个人。 要做到这一点,你就极有可能暴露一些方法SocketThread将访问客户端套接字。 这意味着你必须改变out变量场。

另一种方法是将客户套接字的列表。 但是,这严重破坏封装。 此外,如果插座直接暴露你可能会遇到讨厌的IO /线程安全问题。 更好地隐藏它们背后的一些API(如SocketThread方法),并做适当的内部同步。



Answer 2:

完全实现你在找什么。

服务器

package tcpserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TCPServer {

    private int serverPort = 25565;
    private ServerSocket serverSocket;
    private List<ConnectionService> connections = new ArrayList<ConnectionService>();

    public TCPServer() {
        try {
            serverSocket = new ServerSocket(serverPort);
            System.out.println("Waiting...");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Connected: " + socket);
                ConnectionService service = new ConnectionService(socket);
                service.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new TCPServer();
    }

    class ConnectionService extends Thread {

        private Socket socket;
        private BufferedReader inputReader;
        private PrintWriter outputWriter;
        //private String username;

        public ConnectionService(Socket socket) {
            this.socket = socket;
            try {
                inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                outputWriter = new PrintWriter(socket.getOutputStream(), true);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }

        @Override
        public void run() {
            while (true) {
                try {
                    String receivedMessage = inputReader.readLine();
                    System.out.println(receivedMessage);
                    StringTokenizer stoken = new StringTokenizer(receivedMessage);
                    String fargument = stoken.nextToken();
                    if (fargument.equals("print2all")) {
                        this.sendToAnyone(stoken.nextToken());
                    }
                } catch (IOException ex) {
                    Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NullPointerException e) {
                    System.out.println(e.getMessage());
                } finally {
                    outputWriter.close();
                }

            }
        }

        protected void sendMessage(String message) {
            outputWriter.println(message);
        }

        private void sendToAnyone(String message) {

            for (ConnectionService connection : connections) {
                connection.sendMessage(message);
            }
        }
    }
}

客户

package tcpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class tcpClient extends javax.swing.JFrame {

    private Socket socket;
    private BufferedReader inputReader;
    private PrintWriter outputWriter;

    public tcpClient() {
        connectToServer();
    }

    private void connectToServer() {
        try {
            socket = new Socket(InetAddress.getByName("localhost"), 25565);
            inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            outputWriter = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        new Thread() {
            @Override
            public void run() {
                receiveData();
            }
        }.start();
    }

    private void receiveData() {
        try {
            while (true) {
                System.out.println(inputReader.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendData(String messageToSend) {
        outputWriter.println(messageToSend);
    }

    public void closeSocket() {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                tcpClient client = new tcpClient();
                client.sendData("print2all Hi");
                client.closeSocket();
            }
        });
    }
}


文章来源: I've created a Java server with sockets, just how do print to ALL sockets?