gpt4 book ai didi

java - 如何在p2p应用程序中随机选择谁开始游戏/聊天?

转载 作者:行者123 更新时间:2023-12-03 11:55:36 28 4
gpt4 key购买 nike

大家好,我正在尝试制作一个游戏,两个主持人联系起来,他们将“掷硬币”,并确定谁先出局。我决定从基本代码开始。但是我真的没有主意。

Thread server2 = new Thread(new Server2());
server2.start();
try
{
Thread.sleep(5000);
} catch (InterruptedException ex)
{
System.out.println(" Second host didnt work");
}

try {
Socket skt = new Socket("127.0.0.1", 9090);
String sendString = JOptionPane.showInputDialog(null, "Enter String to Capitalize");

PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.println(sendString);


BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");

while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it

System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}


}

private static class Server2 implements Runnable{

@Override
public void run()
{
System.out.println("Server 2 started it running");
String data = "I come from the 2nd server!";
try {
ServerSocket srvr = new ServerSocket(9092);
Socket skt = srvr.accept();

BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));

PrintWriter out = new PrintWriter(skt.getOutputStream(), true);

while(true){
String input = in.readLine();
if (input == null || input.equals(".")){
break;
}
out.println(input.toUpperCase());
}
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("server 2 didnt work");
}
}

到目前为止,我使服务器线程进入休眠状态,因此它使我有机会启动另一个主线程(基本上具有相同的功能。)

我只是在想如何启动两个服务器,做一个Math.random(不知道我将这个值随机放在哪里),然后决定谁先去。

另外,我将如何更改每个主机之间的转数。
谢谢

最佳答案

import java.util.Random;
public class RandomElement {
private static Random rnd = new Random();

public static Object getRandomElement(Object element1, Object element2) {
if(rnd.nextBoolean()){
return element1;
}
else{
return element2;
}
}
}

该代码将允许您在任何类的2个元素之间随机决定,因此只需将两个主机分别作为element1和element2放入,这将返回一个随机主机,并允许您随机决定一个主机

关于java - 如何在p2p应用程序中随机选择谁开始游戏/聊天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292989/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com