繁体   English   中英

如何在套接字上发送字符串和整数?

[英]How I can send an String and an Integer over a socket?

我的客户端有2个按钮,每个按钮都有一个按钮监听器。

在我的第一个按钮监听器中,我在套接字上发送一个字符串 ,并且在它被截取后我将返回一个整数数组。 没问题。 这是我的代码。

public void rollDice() {

    try {
        DataOutputStream sout1 = new DataOutputStream(socket.getOutputStream());
        String line = "dice";
        PrintStream out1 = new PrintStream(sout1);
        out1.println(line);
    } catch (UnknownHostException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

}

使用第二个侦听器,我想首先发送一个字符串以使服务器进入正确的状态,然后我想发送一个整数来继续进程。 这是我的代码,但它似乎不起作用。 即使我发送“2”,服务器也会打印一个随机数。

public void sendDice() {

    try {
        DataOutputStream sout2 = new DataOutputStream(socket.getOutputStream());
        String line = "pick";
        PrintStream out2 = new PrintStream(sout2);
        out2.println(line);

        out2.write(diceListLength);
    } catch (UnknownHostException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

这是服务器的一面。

public void run() {

        boolean running = true;

        try {

            // Create streams for reading / writing lines of text to the socket
            DataInputStream input = new DataInputStream(s.getInputStream());
            DataInputStream inputInt = new DataInputStream(s.getInputStream());

            ObjectOutputStream output = new ObjectOutputStream(s.getOutputStream());

            // Print a message:
            System.out.println("\nClient from: " + s.getInetAddress() + " port " + s.getPort());

            while(running) {
                String st = input.readLine();

                if (st.equals("dice")) {
                    for (int i = 0; i < diceRolled.length - number; i++) {
                        diceRolled[i] = (int) ( 1 + Math.random() * 6);
                        System.out.print(diceRolled[i] + " ");
                    }
                    output.writeObject(diceRolled);
                    output.reset();
                } else if (st.equals("pick")) {
                    number = inputInt.readInt();
                    System.out.print(number);

                }
            } 
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
         // Always be sure to close the socket
        } finally {
            try {
                if (s != null) {
                    System.out.println(s.getLocalSocketAddress() + " closed.");
                    s.close();
                }                   
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }

尝试在创建PrintStream时设置autoFlush ...在换行或缓冲区已满之前不会发送单个整数。

来自java的文档

autoFlush - 布尔值; 如果为true,则只要写入字节数组,调用其中一个println方法,或者写入换行符或字节('\\ n'),就会刷新输出缓冲区

也很有用:

  1. 使用基于行的消息传递,即第二种消息类型可以是"pick:4" (使用st.startsWith("pick") )然后解析整数。 使用您的代码,您很容易就会失去状态。 (单行消息是“伪原子”)。
  2. 不要在每个侦听器方法中创建DataInputStreams ,使它们成为对象变量(对于PrintStreams来说也是如此......)。 每次点击都不需要(重新)创建对象。

暂无
暂无

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

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