簡體   English   中英

Java TCP Client偵聽和寫入TCP Server

[英]Java TCP Client listening and writing to TCP Server

我有一個用Java編寫的TCP客戶端和一個TCP服務器。 服務器正在等待客戶端的指令,但是也應該能夠將指令發送到客戶端。 我可以使客戶端向服務器發送一些內容並等待回復。 但是我不能讓它像等待消息而不發送任何內容。

TCP客戶端

    public class TCPClient {

    static DataOutputStream toServer;
    static BufferedReader fromServer;
    static Socket socket;

    public static void main(String[] args) throws Exception {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("*************************");
        System.out.println("*       Client          *");
        System.out.println("*************************");
        System.out.println("INSTRUCTION       | EFFECT");
        System.out.println("aktiv             | ready to do something");
        System.out.println("exit              | disconnect");
        System.out.println();
        System.out.print("Please enter the IP-Address of the Server: ");
        String ip = input.readLine();
        System.out.println();

        try {
            socket = new Socket(ip, 9999);
        } catch (Exception e) {
            System.out.println("Can not connect to Server!");
        }

        toServer = new DataOutputStream(socket.getOutputStream());  // Datastream FROM Server 
        fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));     
        while (sendRequest()) {              
            receiveResponse();                 
        }
        socket.close();
        toServer.close();
        fromServer.close();
    }

    private static boolean sendRequest() throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String line;
        boolean holdTheLine = true;          // Connection exists

        System.out.print("> ");
        line = input.readLine();

        switch (line) {
            case "aktiv":
                toServer.writeBytes("active" + '\n');
                break;
            case "exit":
                holdTheLine = false;
                break;
            default:
                break;
        }

        return holdTheLine;
    }

    private static void receiveResponse() throws IOException {
        System.out.println("Server: " + fromServer.readLine() + '\n');
    }
}

TCP服務器

public class TCPServer {
    static boolean connected = true;
    public static void main(String[] args) throws Exception {
        System.out.println("********************************");
        System.out.println("*         Server               *");
        System.out.println("********************************");
        System.out.println("INSTRUCTION | EFFECT");
        System.out.println("ok          | send an ok to client");

        ServerSocket listenSocket = new ServerSocket(9999);

        while (true) {
            final Socket client = listenSocket.accept();

            Thread newClientThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    multithreadedServer(client);
                }
            });
            newClientThread.start();
        }
    }

    public static void multithreadedServer(Socket client) {
        String line;
        final BufferedReader fromClient;
        final DataOutputStream toClient;
        Thread cmdForClient;

        try {
            fromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
            toClient = new DataOutputStream(client.getOutputStream());

            while (connected) {
                cmdForClient = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String line = fromClient.readLine();
                            System.out.println("Client: " + line);
                            if (line.equals("exit")) {
                                connected = false;
                            }
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                });
                cmdForClient.start();

                final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

                try {
                    String reply = input.readLine();
                    if (reply.equals("ok")) {
                            toClient.writeBytes("OK." + '\n');
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
            fromClient.close();
            toClient.close();
            client.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

}

客戶端-服務器方案的典型操作是客戶端將請求發送到服務器。 但是,在對等應用程序中,兩個端點都可能同時充當客戶端和服務器。 唯一的區別是哪個端點打開了連接。 在您的情況下,問題在於只有“服務器”正在使用接收器線程。 在客戶端啟動一個接收器線程,您的問題應該得到解決。 您應該幾乎可以重用客戶機中服務器中的線程代碼。 打開服務器連接后,只需將套接字傳遞給接收線程即可。

編輯:

在您的客戶中:

            Thread newServerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    multithreadedServer(socket);
                }
            });
            newServerThread.start();

其中socket是服務器的套接字。 您可能需要針對客戶端操作的任何細節或差異更新multithreadedServer,但是原理應相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM