简体   繁体   English

Java TCP Client侦听和写入TCP Server

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

I have one TCP-Client and one TCP-Server written in Java. 我有一个用Java编写的TCP客户端和一个TCP服务器。 The Server is waiting for instructions from the Client but should also be able to send instructions to the client. 服务器正在等待客户端的指令,但是也应该能够将指令发送到客户端。 I can make the Client send something to the Server and wait for a reply. 我可以使客户端向服务器发送一些内容并等待回复。 But I can not make it like waiting for a message without sending something before. 但是我不能让它像等待消息而不发送任何内容。

TCP-Client 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-Server 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);
        }
    }

}

The typical operation for a client-server scenario is for the client sending requests to the server. 客户端-服务器方案的典型操作是客户端将请求发送到服务器。 However, in peer to peer applications, both endpoints might act as both clients and servers. 但是,在对等应用程序中,两个端点都可能同时充当客户端和服务器。 The only difference would be which endpoint that opened the connection. 唯一的区别是哪个端点打开了连接。 In your case, the problem is that only the "server" is using a receiver thread. 在您的情况下,问题在于只有“服务器”正在使用接收器线程。 Start a receiver thread at the client side and your problem should be solved. 在客户端启动一个接收器线程,您的问题应该得到解决。 You should pretty much be able to just reuse your threaded code from the server in the client. 您应该几乎可以重用客户机中服务器中的线程代码。 Just pass the socket to the receive thread after opening the connection to the server. 打开服务器连接后,只需将套接字传递给接收线程即可。

EDIT: 编辑:

In your client: 在您的客户中:

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

where socket, is the socket to the server. 其中socket是服务器的套接字。 You may need to update multithreadedServer for any specifics or differences for the clients operations, but the principle should be the same. 您可能需要针对客户端操作的任何细节或差异更新multithreadedServer,但是原理应相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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