使用 java Socket 从客户端向服务器端传文件

 服务器端类 SocketServer

 

public class SocketServer {
 protected int listenPort = 3000;

 public static void main(String[] args) {
  SocketServer server = new SocketServer();
  server.acceptConnections();
 }
 /**
  * 建立链接
  *
  */
 public void acceptConnections() {
  try {
   ServerSocket server = new ServerSocket(listenPort);
   Socket socket = null;
   while (true) {
    socket = server.accept();
    //handleConnection(socket);
    new ServerThread(socket).start();
   }
  } catch (BindException e) {
   System.out.println("Unable to bind to port " + listenPort);
  } catch (IOException e) {
   System.out.println("Unable to instantiate a ServerSocket on port: "
     + listenPort);
  }

 }
}

服务器端接收线程类

public class ServerThread extends Thread {
 private Socket socket;

 public ServerThread(Socket socket)
 {
  this.socket = socket;
 }


 public void run(){

  try {

   DataInputStream inputStream = null;
   try {
    inputStream = new DataInputStream(new BufferedInputStream(
      socket.getInputStream()));
   } catch (Exception e) {
    System.out.print("接收消息缓存错误/n");
    return;
   }
   try {
    // 本地保存路径,文件名会自动从服务器端继承而来最好是web工程里的一个路径。
    String savePath = "E://";
    int bufferSize = 8192;
    byte[] buf = new byte[bufferSize];
    long len = 0;
    savePath += inputStream.readUTF();
    DataOutputStream fileOut = new DataOutputStream(
      new BufferedOutputStream(new BufferedOutputStream(
        new FileOutputStream(savePath))));
    len = inputStream.readLong();
    System.out.println("文件的长度为:" + len + "/n");
    System.out.println("开始接收文件!" + "/n");
    while (true) {
     int read = 0;
     if (inputStream != null) {
      read = inputStream.read(buf);
     }
     if (read == -1) {
      break;
     }
     //System.out.println(buf.toString());
     fileOut.write(buf, 0, read);
    }
    System.out.println("接收完成,文件存为" + savePath + "/n");
    fileOut.flush();
    fileOut.close();
    inputStream.close();
   } catch (Exception e) {
    System.out.println("接收消息错误" + "/n");
    return;
   }
  } catch (Exception e) {
   System.out.println("Error handling a client: " + e);
  }
  
 }

}

 

客户端发送文件类

public class SocketClient extends Thread{
 protected String hostIp ="127.0.0.1";
 protected int hostPort = 3000;
 InputStream fis;
 DataOutputStream ps;
 File fi;
 DataInputStream dis;
 String path;
 Socket client;
 
 public SocketClient() {
 }
 public SocketClient(String path) {
  this.path = path;
 }
 public SocketClient(String path,String aHostIp, int aHostPort) {
  this.path = path;
  this.hostIp = aHostIp;
  this.hostPort = aHostPort;
 }

 public static void main(String[] args) {
  SocketClient client = new SocketClient();
  String path = "f://35.xml";  //测试文件
  client.sendMessage();
 }
 public void run(){
  sendMessage();
 }
 
 /**
  * 将连接到远程服务器
  */
 public void setUpConnection() {
  try {
   client = new Socket(hostIp, hostPort);
   fis = new FileInputStream(path);
   ps = new DataOutputStream(client.getOutputStream());
   fi = new File(path);
  } catch (UnknownHostException e) {
   System.out
     .println("Error setting up socket connection: unknown host at "
       + hostIp + ":" + hostPort);
  } catch (IOException e) {
   System.out.println("Error setting up socket connection: " + e);
  }

 }

 /**
  * 将向远程服务器请求 path 的内容
  *
  * @param path
  * @return
  */
 public void sendMessage() {
  setUpConnection();
  if(client == null)
   return ;
  try {
   // 将文件名及长度传给客户端。
   ps.writeUTF(fi.getName());
   ps.flush();

   ps.writeLong((long) fi.length());
   ps.flush();
   int bufferSize = 8192;
   byte[] buf = new byte[bufferSize];
   while (true) {
    int read = 0;
    if (fis != null) {
     read = fis.read(buf);
    }
    if (read == -1) {
     break;
    }
    ps.write(buf, 0, read);
   }
   ps.flush();

   System.out.println("文件传输完成");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {

   // 注意关闭socket链接哦,不然客户端会等待server的数据过来,
   // 直到socket超时,导致数据不完整。
   try {
    ps.close();
    fis.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }
 }

}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值