随机数生成始终返回相同的值

时间:2015-07-16 01:20:21

标签: java sockets client server port

我正在尝试运行一个简单的程序,其中服务器侦听连接,接收客户端请求并发送消息。也许是微不足道的,但我的困惑是关于服务器的行为。代码如下:

服务器代码:

import java.net.*;
import java.io.*;
import java.util.*;

public class haikuServer {

    private static String chooseHaiku() {
        String[] haiku = new String[3];
        haiku[0] = "Pawprints disappear"+"\n"+"into the snowy glen, but"+"\n"+"fox waits patiently.";
        haiku[1] = "Whispering winds cry"+"\n"+"while frenzied snowflakes scatter,"+"\n"+"searching for others.";
        haiku[2] = "The path, hard and long"+"\n"+"brings dawn with passage of time"+"\n"+"and then my heart sings.";

        Random t = new Random();
        int ch = t.nextInt(3); 
        return haiku[ch];
    }

    public static void main(String[] args) {
        try {
            ServerSocket sock = new ServerSocket(5575);

            while (true) {
                Socket client = sock.accept();

                PrintWriter pout = new PrintWriter(client.getOutputStream(), true);

                String haiku = chooseHaiku();
                pout.println(haiku);
                client.close();
            }
        } catch (Exception e) {}
    }
}

客户代码:

import java.net.*;
import java.io.*;

public class haikuClient {
    public static void main(String[] args) {
        try {
            Socket sock = new Socket("127.0.0.1", 5575);

            InputStream in = sock.getInputStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));

            System.out.println("\nHaiku:\n");
            String line;
            while ((line = bin.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println();

            /* Close the socket connection */
            sock.close();

        } catch (IOException ioe) {
            System.err.println(ioe);
        }
    }
}

代码工作正常。我编译了这两个文件。为了运行它们,我使用:java haikuServer& (&在后台运行程序)然后haikuClient。我的问题是我尝试多次运行haikuClient但是所有时间,服务器选择的选择是第一个,即ha句[0]而不是其他。为什么会这样?

1 个答案:

答案 0 :(得分:3)

它与网络无关,而是与随机数生成有关。

您观察到只返回数组中的第一项是不正确的......当我运行您的代码时,它会在数组的前两个元素之间交替显示。

nextInt(2)的文档说明了这一点:

  

返回一个伪随机数,在0之间均匀分布的int值   (包括)和指定值(不包括)

所以这个调用:nextInt(3)返回0到1之间的数字。如果你运行客户端足够多次,你会看到Haiku在数组的第一个和第二个之间交替返回。要获取您想要使用的三个随机元素中的任何一个// first query only to get count MATCH (x:Brand) WITH count(*) as total // query again to get results :( MATCH (o:Brand) WITH total, o ORDER BY o.name SKIP 5 LIMIT 5 WITH total, collect({uuid:o.uuid, name:o.name}) AS brands RETURN {total:total, brands:brands}