当我运行简单的网络程序时,我无法在Java中进行任何联网我无法获得连接,即使使用本地主机, 错误:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at EchoClient.main(EchoClient.java:8)
这是该计划:
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoClient{
public static void main(String[] args) {
try{
Socket client = new Socket(InetAddress.getLocalHost(), 1234);
InputStream clientIn = client.getInputStream();
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut);
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
Scanner stdIn = new Scanner(System.in);
System.out.println("Input Message:");
pw.println(stdIn.nextLine());
System.out.println("Recieved Message:");
System.out.println(br.readLine());
pw.close();
br.close();
client.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
我使用Windows 7,我已经关闭了Windows防火墙而且我没有防病毒。
答案 0 :(得分:2)
正如我在评论中所写,检查服务器(类似EchoServer?)是否正常运行。
但是当你成功连接时还有其他问题。 pw.println(stdIn.nextLine());
可能不会将内容发送到服务器,您需要pw.flush();
来真正发送内容,或者您可以使用autoflushing创建PrintWriter
:
pw = new PrintWriter(clientOut, true);
如果您需要EchoServer
我刚刚写了一个与您的客户端一起使用的内容,如果您添加我上面描述的刷新:
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(1234);
while (true) {
// accept the connection
Socket s = ss.accept();
try {
Scanner in = new Scanner(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
// read a line from the client and echo it back
String line;
while ((line = in.nextLine()) != null)
out.println(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
s.close();
}
}
}
}
您可以使用telnet localhost 1234
尝试。
答案 1 :(得分:1)
仔细检查您的本地EchoServer是否已在端口1234上启动并运行。如果该端口上没有服务器正在运行,您将无法连接。
答案 2 :(得分:1)
我在Windows 7中的解决方案是打开“简单TCP / IP服务”。这里描述了:http://www.windowsnetworking.com/articles_tutorials/windows-7-simple-tcpip-services-what-how.html