客户端控制台总显示异常:java.net.ConnectException: Connection refused: connect
/**
 * 服务端
 */
public class Service {
public static void main(String []args){
try {
ServerSocket server = new ServerSocket(9111);
Socket socket = server.accept(); //阻塞
InputStream in = socket.getInputStream();
byte[] b = new byte[1024];
OutputStream out = new FileOutputStream("e:\\1.txt");
while (in.read(b)!=-1) {
 out.write(b);
 out.flush();
}
out.close();
System.out.println("文件接收结束");
} catch (IOException e) {
e.printStackTrace();
}
}
}/**
 * 客户端
 */
public class Client2 {
public static void main(String[] args) {
OutputStream out = null;
try {
Socket socket = new Socket("127.0.0.1",8888);
InputStream in = socket.getInputStream();
out = new FileOutputStream("e:\\123.txt");
byte[]data = new byte[1024];
int length = 0;
while((in.read(data))!=-1){
out.write(data );out.flush();
}
out.close();
System.out.println("文件接收结束...");
socket.close();
System.out.println("客户端结束");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

解决方案 »

  1.   

    不好意思 代码粘错了 服务端的代码应该是:public class Service2 { public static void main(String[] args)  {
    InputStream in = null;
    try{
    ServerSocket service = new ServerSocket(8888);
    Socket socket = service.accept();//阻塞
    OutputStream out = socket.getOutputStream();
    byte [] data = new byte[1024];
    //开始读取文件
    in = new FileInputStream("e:\\SNET.txt");
     
    while (in.read(data)!=-1) {
    out.write(data,0,1024);
    out.flush();
    }
     
    in.close();
    System.out.println("传送文件结束...");
    service.close();
    System.out.println("服务器关闭");
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }