【问题标题】:Java TCP Client listening and writing to TCP ServerJava TCP Client 监听和写入 TCP Server
【发布时间】:2016-08-26 10:51:24
【问题描述】:

我有一个用 Java 编写的 TCP-Client 和一个 TCP-Server。服务器正在等待来自客户端的指令,但也应该能够向客户端发送指令。 我可以让客户端向服务器发送一些东西并等待回复。但是我不能让它像等待消息而不发送之前一样。

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

}

【问题讨论】:

    标签: java sockets tcp


    【解决方案1】:

    客户端-服务器方案的典型操作是客户端向服务器发送请求。但是,在点对点应用程序中,两个端点都可以充当客户端和服务器。唯一的区别是打开连接的端点。在您的情况下,问题在于只有“服务器”正在使用接收器线程。在客户端启动接收器线程,您的问题应该得到解决。您几乎应该能够在客户端中重用来自服务器的线程代码。打开与服务器的连接后,只需将套接字传递给接收线程即可。

    编辑:

    在您的客户中:

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

    其中socket,是服务器的socket。您可能需要针对客户端操作的任何细节或差异更新 multithreadedServer,但原则应该相同。

    【讨论】:

    • 您能否给我看一个简短的示例,说明您所说的“来自客户端的服务器的线程代码”是什么意思?
    • 我的意思是,您还需要在客户端代码中使用线程,而不仅仅是在服务器中。由于您已经在服务器中有代码,您可以重复使用该代码。
    猜你喜欢
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多