问题描述
- java网络socket编程过程中遇到的问题
-
运行代码
import java.io.*;
import java.net.*;
public class InetAddressDemo {
public static void main(String[] args) {
Socket socket = null;
InputStream is = null;
OutputStream os = null;
String serverIP = "127.0.0.1";
int port = 10000;
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) {}
}}}出现下面错误
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.(Socket.java:366)
at java.net.Socket.(Socket.java:180)
at InetAddressDemo.main(InetAddressDemo.java:20)第一次改了端口号10000变成8000,成功编译;第二次以及后来程序依旧显示上面的错误,求大神指点一下!!
解决方案
端口被占用了,关闭服务就可以了
时间: 2024-11-02 23:06:59