基于Socket上传客户端

来源:互联网 发布:手机拍摄软件 编辑:程序博客网 时间:2024/06/07 00:09
/**
 *
 */
package com.yb.tcp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @ClassName ClientDemo
 * @Description TODO
 * @author yanbiao
 * @email yanbiao_it@sina.com
 * @date 2015年3月4日
 */

public class ClientDemo {
    /**
     * 客户端上传文件
     *
     * @Description: TODO
     * @param fileName
     *            上传文件名称
     * @param ipAddress
     *            服务端ip地址
     * @param port
     *            服务端监听端口
     * @return boolean 文件上传是否成功
     */
    public static boolean upload(String fileName, String ipAddress, int port) {
        Socket socket = null;
        FileInputStream fis = null;
        try {
            socket = new Socket(ipAddress, port);

            File file = new File(fileName);

            fis = new FileInputStream(file);

            OutputStream os = socket.getOutputStream();// 获取socket输出流

            os.write(file.getName().getBytes());// 向服务端发送上传文件名称

            String info = servInfoBack(socket);// 接收服务端返回消息

            if (ConstantUtil.STATUS_SUCESS.equals(info)) {// 如服务端创建文件成功,则继续上传文件

                byte[] buf = new byte[1024];

                int len = 0;

                while ((len = fis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }

                socket.shutdownOutput();// 通知服务端客户端数据发送结束

                String serverMsg = servInfoBack(socket);

                ConstantUtil.print("upload result:" + serverMsg);
            } else {
                ConstantUtil.print(info);
                return false;
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
    
    public static boolean downloadFile(String fileName, String ipAddress, int port){
        
        return true;
    }

    private static String servInfoBack(Socket sock) throws IOException {
        InputStream sockIn = sock.getInputStream(); // 定义socket输入流
        byte[] bufIn = new byte[1024];
        int lenIn = sockIn.read(bufIn); // 将服务端返回的信息写入bufIn字节缓冲区
        String info = new String(bufIn, 0, lenIn);
        return info;
    }

}


0 0