在单独的线程上获取套接字数据,然后将其传递给主线程

编辑了我的问题以进行澄清和代码:


我的目标是将我的字符串数据从我的后台线程传递到我的主应用程序线程。任何帮助表示赞赏。


这是创建主后台线程的代码。这位于我的 Server.java 类中


public class Server {


boolean isConnected = false;

Controller controller = new Controller();


public void startHost() {

    Thread host = new Thread(() -> {

        Controller controller = new Controller();

        ServerSocket server = null;


        try {

            server = new ServerSocket(GeneralConstants.applicationPort);


        } catch (BindException e2) {

            System.out.println("Port Already in Use!");


        } catch (IOException e) {

            //do nothing


        }


        while (true) {

            if (server == null) { break; }


            try {

                Socket client = server.accept();


                System.out.println("Client Connected: " + isConnected);


                if (!isConnected) {

                    controller.createClientHandler(client);

                    isConnected = true;

                    System.out.println("Client Connected: " + isConnected);

                }


            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();


            }

        }

    });


    host.setDaemon(true);

    host.start();


}

下面是连接客户端时调用的代码,位于我的 Controller.java 类中。


    public synchronized void createClientHandler(Socket client) {

    boolean alreadyConnected = false;


    if (alreadyConnected) {

        //do NOT assign multiple threads for each client


    } else {

        ClientHandler handleClients = new ClientHandler("client", client);


    }


}

然后该程序为我的客户端创建了两个后台线程,一个用于管理接收消息和发送消息。


public ClientHandler(String name, Socket s) {

    clientSocket = s;

    clientName = name;


    receiveThread = new Thread(this::receive);

    sendThread = new Thread(this::send);


    connected = clientSocket.isConnected();


    receiveThread.start();

    sendThread.start();


}


如何从主线程访问我的字符串数据而不会为空?




慕雪6442864
浏览 233回答 1
1回答

慕标5832272

开始考虑设计。在网络应用程序中,您通常必须管理以下职责:已连接的客户端及其状态(连接状态、心跳……)收到客户的消息发送给客户端的消息将这些职责分开以保持代码干净、可读和可维护是有意义的。分离可以意味着线程和类。例如,您可以按如下方式实现它:该类ClientAcceptor负责打开套接字并接受客户端。一旦客户端连接,它将进一步的工作委托给控制器,然后等待其他客户端:public class ClientAcceptor implements Runnable {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; while (true) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ServerSocket server;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; server = new ServerSocket(1992);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Socket client = server.accept();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (client.isConnected()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controller.createClientHandler(client);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后控制器可以创建一个处理程序(如果控制器决定这样做,例如它也可以拒绝客户端)。本ClientHandler类可以如下所示:public class ClientHandler {&nbsp; &nbsp; private Thread receiveThread;&nbsp; &nbsp; private Thread sendThread;&nbsp; &nbsp; private boolean connected;&nbsp; &nbsp; private Socket clientSocket;&nbsp; &nbsp; private String clientName;&nbsp; &nbsp; private LinkedBlockingDeque<byte[]> sendQueue;&nbsp; &nbsp; public ClientHandler(String name, Socket s) {&nbsp; &nbsp; &nbsp; &nbsp; clientSocket = s;&nbsp; &nbsp; &nbsp; &nbsp; clientName = name;&nbsp; &nbsp; &nbsp; &nbsp; receiveThread = new Thread(() -> receive());&nbsp; &nbsp; &nbsp; &nbsp; sendThread = new Thread(() -> send());&nbsp; &nbsp; &nbsp; &nbsp; connected = clientSocket.isConnected();&nbsp; &nbsp; &nbsp; &nbsp; receiveThread.start();&nbsp; &nbsp; &nbsp; &nbsp; sendThread.start();&nbsp; &nbsp; }&nbsp; &nbsp; private void receive() {&nbsp; &nbsp; &nbsp; &nbsp; BufferedInputStream in = null;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in = new BufferedInputStream(clientSocket.getInputStream());&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; connected = false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; while (connected) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] bytes = in.readAllBytes();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (bytes != null && bytes.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; controller.handleReceivedPacket(clientName, bytes);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; private void send() {&nbsp; &nbsp; &nbsp; &nbsp; BufferedOutputStream out = null;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out = new BufferedOutputStream(clientSocket.getOutputStream());&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; connected = false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; while (connected) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] toSend = sendQueue.getFirst();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (toSend != null && toSend.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out.write(toSend);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void send(byte[] packet) {&nbsp; &nbsp; &nbsp; &nbsp; sendQueue.add(packet);&nbsp; &nbsp; }&nbsp; &nbsp; public void close() {&nbsp; &nbsp; &nbsp; &nbsp; connected = false;&nbsp; &nbsp; }}该ClientHandler负责接收和发射数据。如果数据包到达,它会通知控制器,控制器会解析数据包。的ClientHandler还提供了一个公共API来发送数据(其被存储在队列中,并通过一个线程来处理),并关闭连接。上面的代码示例既未经测试,也不完整。以它为起点。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java