【发布时间】:2020-02-12 05:24:49
【问题描述】:
我大吃一惊。
我从https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java获取代码
为服务器。和 https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java
为客户。我做了一些小的改动。主要是为了没有来回回响。相反,服务器应该不断地以 2 秒的延迟发送相同的字符串。但我就是不明白为什么客户不工作。 它发送异常消息: 无法获得与 127.0.0.1 的连接的 I/O 我运行服务器:java 6788 和客户:127.0.0.1 6788 我尝试了其他端口。
我在 Eclipse 中执行此操作,因此我在运行类之前在 Runconfiguration 中设置了参数。我先启动服务器。我在 Eclipse 之外的终端中尝试过。没有什么可以让它工作。 基本上,客户端应该连接到服务器并使用 System.out.println() 输出服务器依次输出到客户端的内容。但什么也没有发生。 怎么了?
客户:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
) {
String userInput;
while (true) {
System.out.println("recieved: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
服务器:
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
System.out.println(args[0]);
InetAddress add = InetAddress.getLocalHost();
System.out.println(add.getHostAddress());
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream());
) {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("HELLO!");
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
【问题讨论】:
标签: java sockets inputstream