Java套接字自动通信

时间:2018-07-08 13:38:35

标签: java sockets datainputstream

服务器和客户端之间的通讯出现问题。我试图找出一种自动通信的方式,因为它们必须交换一些参数。但是,使用我编写的代码,服务器要么在客户端确认消息后继续向客户端发送相同的消息,要么客户端什么也没收到。套接字和所有东西都已经设置好了。两个代码示例中的函数sendString()和receiveString()是相同的。有适当的方法吗?我不明白为什么这行不通...

服务器:

String buffer;
    while(true){
        buffer = client.receiveString();
        if(buffer != null && buffer.equals("ready")){
            System.out.println("Client is ready");
            client.sendString("ready");
            while(true){
                buffer = client.receiveString();
                if(buffer != null && buffer.equals("k")){
                    System.out.println("stopped");
                    break;
                }
            }
            break;
        }
    }

public String receiveString() throws IOException{         //From the client class
    if(dataIn.available() > 0){
        int length = dataIn.readInt();
        byte[] b = new byte[length];
        dataIn.readFully(b, 0, b.length);

        return new String(b, Charset.forName("UTF-8"));
    }
    return null;
}

public void sendString(String msg) throws IOException{
    byte[] b = msg.getBytes(Charset.forName("UTF-8"));

    dataOut.writeInt(b.length);
    dataOut.write(b);
}

客户:

String buffer;
while(true){
    sendString("ready");
    buffer = receiveString();
    if(buffer!=null)
        System.out.println(buffer);
    if(buffer != null && buffer.equals("ready")){   
        System.out.println("Server is ready");
        sendString("k");
        break;
    }
}

1 个答案:

答案 0 :(得分:0)

此代码可能适用于您的情况:

Client.java

public class Client {
    public static void main(String[] args) throws Exception {
        try (Socket socket = new Socket("localhost", 8080)) {
            try (BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
                 Scanner in = new Scanner(socket.getInputStream())) {
                System.out.println("Client: sending ready.");
                writeLine("ready", out);
                System.out.println("Client: sent ready.");

                String line = in.nextLine();
                if ("ready".equals(line)) {
                    System.out.println("Client: server is ready");
                    writeLine("k", out);
                }
            }
        }
    }

    private static void writeLine(final String line, final BufferedOutputStream out) throws IOException {
        out.write((line +"\n").getBytes());
        out.flush();
    }
}

Server.java:

public class Server {

    public static void main(String[] args) throws Exception {
        boolean running = true;
        try (ServerSocket socket = new ServerSocket(8080, 0)) {
            while (running) {
                System.out.println("Waiting for client accept.");
                try (final Socket client = socket.accept();
                     final Scanner in = new Scanner(client.getInputStream());
                     final BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream())) {
                    System.out.println("Waiting for client ready.");
                    String line = readLine(in);

                    if ("ready".equals(line)) {
                        writeLine("ready", out);

                        while (running) {
                            line = readLine(in);
                            if (line != null && line.equals("k")) {
                                System.out.println("Server: received stop signal");
                                running = false;
                            } else {
                                Thread.sleep(100);
                                System.out.println("Server: waiting for command.");
                            }
                        }
                    }
                }
            }
        }
    }

    private static String readLine(final Scanner in) {
        String line = in.nextLine();
        System.out.println("Server: client sent " + line);

        return line;
    }

    private static void writeLine(final String line, final BufferedOutputStream out) throws IOException {
        out.write((line + "\n").getBytes());
        out.flush();
    }
}

那么这里发生了什么? 服务器套接字等待客户端。如果客户端连接,它将等待其发送消息(以阻塞方式!)。如果“准备就绪”,它将检查其他命令。

注意:这一次仅适用于单个服务器<->客户端连接。如果这适合您的应用程序,Dunno。如果客户端发送“ k”,服务器将关闭,就像您的情况一样。