我有一个正在编写的服务器/客户端程序,其中服务器向客户端发送消息,反之亦然。它工作得很好,除了方法中的out.println
语句printRemoteAddress()
。"HELLO1"
并"HELLO2"
打印到客户端,但"HELLO3
" 没有。
我的问题是,为什么不"HELLO3"
打印到客户端,而是前两个呢?
服务器代码:
class Worker extends Thread {
Socket sock;
Worker (Socket s) {sock = s;}
public void run() {
PrintStream out = null;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintStream(sock.getOutputStream());
try {
String name;
name = in.readLine();
System.out.println("Looking up " + name);
printRemoteAddress(name, out);
} catch (IOException x) {
System.out.println("Server read error");
x.printStackTrace();
}
sock.close();
} catch (IOException ioe) {System.out.println(ioe);}
}
static void printRemoteAddress (String name, PrintStream out) {
try {
out.println("HELLO1");
out.println("HELLO2");
out.println("HELLO3");
InetAddress machine = InetAddress.getByName(name);
} catch(UnknownHostException ex) {
out.println ("Failed in attempt to look up " + name);
}
}
public class InetServer {
public static void main(String a[]) throws IOException {
int q_len = 6;
int port = 2000;
Socket sock;
ServerSocket servsock = new ServerSocket(port, q_len);
System.out.println
("Inet server 1.8 starting up, listening at port 2000.\n");
while (true) {
sock = servsock.accept();
new Worker(sock).start();
}
}
客户代码:
public class InetClient {
public static void main (String args[]) {
String serverName;
if (args.length < 1) serverName = "localhost";
else serverName = args[0];
System.out.println("Inet Client, 1.0.\n");
System.out.println("Using server: " + serverName + ", Port: 2000");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String name;
do {
System.out.print("Enter hostname of IP address: ");
System.out.flush();
name = in.readLine();
if (name.indexOf("stop") < 0)
getRemoteAddress(name, serverName);
} while (name.indexOf("stop") < 0);
System.out.println("Process stopped.");;
} catch (IOException x) {x.printStackTrace();}
}
static void getRemoteAddress (String name, String serverName) {
Socket sock;
BufferedReader fromServer;
PrintStream toServer;
String textFromServer;
try {
sock = new Socket(serverName, 2000);
fromServer = new BufferedReader (new InputStreamReader(sock.getInputStream()));
toServer = new PrintStream(sock.getOutputStream());
toServer.println(name);
toServer.flush();
for (int i = 1; i <3; i++) {
textFromServer = fromServer.readLine();
if (textFromServer != null) System.out.println(textFromServer);
}
sock.close();
} catch (IOException x) {
System.out.println("Socket error.");
x.printStackTrace();
}
}
}
for (int i = 1; i <3; i++) {
嗡嗡声。这迭代了两次,而不是三次。它应该是
for (int i = 1; i <= 3; i++) {
事实上,完全不将 3 硬连线会更有意义:
while ((textFromServer = fromServer.readLine()) != null {
System.out.println(textFromServer);
}
该println()
不是“跳过”,而是PrintStream
被缓冲,并不会在新行自动冲洗。您可以使用第二个参数来构造它,或者flush()
根据需要调用,或者使用PrintWriter
.
您还应该关闭PrintStream/PrintWriter
,而不是Socket
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句