【发布时间】:2015-07-16 01:20:21
【问题描述】:
我正在尝试运行一个简单的程序,其中服务器侦听连接、接收客户端请求并发送消息。也许微不足道,但我的困惑是关于服务器的行为。代码如下:
服务器代码:
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 但始终,服务器选择的是第一个,即 haiku[0] 而不是其他的。为什么会这样?
【问题讨论】:
-
永远不要默默吞下异常
catch (Exception e) {} -
所以你的问题与套接字无关,而是为什么随机不按你的预期工作 - 对。
-
正如我在下面的答案中也提到的,也许我又犯了一些错误,但我尝试运行客户端超过 10 次,仍然只得到第一个。
-
保持你的问题简短。如果您包含太多不相关的内容,其他人不会花时间回答您。
-
还有,俳句很无聊:)
标签: java sockets client server port