java 网络编程
我执行一个非常简单的socket程序都出错!要崩溃了!我关闭了防火墙也不行,试了Ping 127.0.0.1是可以的,而且我查了这个端口也没有被占用,怎么解决?
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at com.hxw.socket.SimpleSocketClient.main(SimpleSocketClient.java:22)
java.lang.NullPointerException
at com.hxw.socket.SimpleSocketClient.main(SimpleSocketClient.java:37)
源码在此:
package com.hxw.socket; import java.io.*; import java.net.*; /** * 简单的Socket客户端 功能为:发送字符串“Hello”到服务器端,并打印出服务器端的反馈 */ public class SimpleSocketClient { public static void main(String[] args) { Socket socket = null; InputStream is = null; OutputStream os = null; // 服务器端IP地址 String serverIP = "127.0.0.1"; // 服务器端端口号 int port = 10002; // 发送内容 String data = "Hello"; try { // 建立连接 socket = new Socket(serverIP, port); // 发送数据 os = socket.getOutputStream(); os.write(data.getBytes()); // 接收数据 is = socket.getInputStream(); byte[] b = new byte[1024]; int n = is.read(b); // 输出反馈数据 System.out.println("服务器反馈:" + new String(b, 0, n)); } catch (Exception e) { e.printStackTrace(); // 打印异常信息 } finally { try { // 关闭流和连接 is.close(); os.close(); socket.close(); } catch (Exception e2) { e2.printStackTrace(); } } } }