+-

运行简单的联网程序时,即使使用本地主机,也无法建立连接,因此无法使用 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防火墙,但没有防病毒软件.
最佳答案
正如我在评论中所写,请检查服务器(如EchoServer?)是否已启动并正在运行.
但是,当您成功连接时,还有其他问题. pw.println(stdIn.nextLine());可能不会将内容发送到服务器,则需要执行pw.flush();.真正发送内容,或者您可以使用自动刷新功能创建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.
点击查看更多相关文章
转载注明原文:Java网络问题:java.net.ConnectException:连接被拒绝:connect - 乐贴网