我正在尝试在此处实施此示例:Reading from and Writing to a Socket
我将代码复制并粘贴到NetBeans中。我将端口名称“taranis”更改为“localhost”并尝试运行该示例,但我收到错误:
运行:无法获得与localhost连接的I / O. Java结果:1 建立成功(总时间:1秒)
我还尝试用localhost替换我的笔记本电脑的实际主机名,但它也给出了类似的错误。你能帮助确定我做错了什么吗?
编辑:关于马克的推荐,当我替换
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
与
e.printStackTrace();
我明白了:
run:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at EchoClient.main(EchoClient.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
答案 0 :(得分:3)
echo服务没有收听。为什么不写自己的?运行下面的应用程序并更改您的客户端以连接到同一端口(8000)。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private static final int PORT = 8000;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Echo server started");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("echoing: " + inputLine);
out.println(inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
顺便说一下,下一个例子(knock-knock服务器)确实有效,并提供了一个使用'协议'类的好例子。
答案 1 :(得分:1)
我不认为默认情况下echo服务正在运行,当我在Win XP客户端上尝试快速测试时,它不起作用:
H:\>telnet localhost 7
Connecting To localhost...Could not open connection to the host, on port 7:
Connect failed
H:\>
因此,为了使代码正常工作,您可以尝试将其指向运行echo服务的服务器。
答案 2 :(得分:1)
为了将来参考,默认情况下通常禁用echo服务。我正在使用Windows 7,启用它我按照此处的说明进行操作:
http://www.windowsnetworking.com/articles_tutorials/windows-7-simple-tcpip-services-what-how.html
之后,示例对我来说很好。
对于XP: