JAVA Socket Tcp文件传输

Java Socket TCP通信 –传输数据篇

举个栗子:客户端

创建外部调用接口

package client;


import java.io.IOException;

/**
 * File: LClient.java
 * Create: 2017-06-22 13:16
 */

public interface LClient {

    /**
     * 创建socket连接,并准备接收数据。
     * @param ip
     * @param port
     */
    void connect(String ip, int port);

    /**
     * 断开连接。
     */
    void disConnect();

    /**
     * 是否是连接状态
     * @return
     */
    boolean isConnected();

    /**
     * 上传文件方法
     * @param fileName
     */
    void sendFile(String fileName) throws IOException;

    /**
     * @return 返回socket连接状态
     */
    ConnectEnum connect();
}

创建TcpClient

package client;

import java.io.*;
import java.net.Socket;

/**
 * Created by ejiang on 2017-06-16.
 */

public class TcpClient implements LClient {
    private DataInputStream dataInputStream; //输入流
    private DataOutputStream dataOutputStream; //输出流
    private SocketIOCallback socketIOCallback;
    private Socket socket;

    public TcpClient(SocketIOCallback socketIOCallback) {
        this.socketIOCallback = socketIOCallback;
    }

    @Override
    public void connect(String ip, int port) {
        if (isConnected()) {
            disConnect();
        }
        int connectNum = 0;
        boolean isConnect = false;
        while (connectNum < 5) {
            try {
                connectNum++;
                //1.创建客户端Socket,指定服务器地址和端口
                socket = null;
                socket = new Socket(ip,port);
                if (socket.isConnected()) {
                    //获取输出流
                    dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    //获取输入流
                    dataInputStream = new DataInputStream(socket.getInputStream());
                    isConnect = true;
                }
                break;
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        if (isConnect) {
            readerServerPush();
        } else {
            System.err.println("连接失败请检查网络~");
        }

    }

    /**
     * 读取服务端推送数据流
     */
    private void readerServerPush() {
        if (socket != null) {
            synchronized (TcpClient.class) {
                if (isConnected()) {
                    try {
                        byte[] bytes = new byte[1];
                        dataInputStream.read(bytes);
                        byte[] bytes1 = new byte[Integer.parseInt(new String(bytes))];
                        dataInputStream.read(bytes1);
                        String serverPush = new String(bytes1);
                        System.out.print(serverPush);
                        socketIOCallback.onReceive(serverPush);
                    } catch (IOException e) {
                        e.printStackTrace();
                        socketIOCallback.onConnectFailed(e);
                    }
                }
            }
        }

    }

    @Override
    public void disConnect() {
        if (socket != null) {
            try {
                dataInputStream.close();
                dataOutputStream.close();
                socket.close();
                socket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean isConnected() {
        return socket != null && socket.isConnected();
    }

    @Override
    public void send(byte[] bytes, ISendCallBack callback) throws IOException {
        if(socket!=null){
            synchronized (TcpClient.class){
                if(isConnected()){
                    dataOutputStream.write(bytes);
                    dataOutputStream.flush();
                }
            }
        }
    }

    @Override
    public void send(String strData) {

    }

    @Override
    public void sendFile(String fileName) throws IOException {
        if(socket!=null){
            synchronized (TcpClient.class){
                if(isConnected()){
                    File file = new File(fileName);
                    if(file.exists()){
                        //上传文件类型标识
                        dataOutputStream.writeInt(0);
                        dataOutputStream.flush();
                        //上传文件名称
                        dataOutputStream.writeUTF(file.getName());
                        dataOutputStream.flush();
                        //上传文件的长度
                        dataOutputStream.writeLong(file.length());
                        dataOutputStream.flush();
                        //上传文件数据流
                        byte[] bytes = new byte[1024];
                        int length = 0;
                        long progress = 0;
                        FileInputStream fileInputStream = new FileInputStream(file);
                        while ((length = fileInputStream.read(bytes,0,bytes.length))!=-1){
                            dataOutputStream.write(bytes,0,length);
                            dataOutputStream.flush();
                            progress += length;
                            System.out.println("| " + (100*progress/file.length()) + "% |");
                        }
                    }else{
                        return;
                    }

                }
            }
        }
    }

    @Override
    public ConnectEnum connect() {
        return null;
    }
}

服务端:

创建服务端连接初始化类(开启线程连接支持多个client连接)

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by ejiang on 2017-06-16.
 */
public class TcpServerHelper {
    public TcpServerHelper() {
        initServerSocket();
    }

    private void initServerSocket() {
        try {

            ServerSocket serverSocket = null;
            serverSocket = new ServerSocket(6033);
            if(serverSocket==null){
                return;
            }
            //记录客户端的数量
            int count = 0;
            System.err.println("***服务器即将启动,等待客户端的连接***");
            //循环监听等待客户端的连接
            while (true) {
                Socket socket = null;
                //调用accept()方法开始监听,等待客户端的连接
                socket = serverSocket.accept();
                //创建一个新的线程
                ServerSocketThread serverThread = new ServerSocketThread(socket);
                //启动线程
                serverThread.start();
                count++;//统计客户端的数量
                System.out.println("客户端的数量:" + count);
                InetAddress address = socket.getInetAddress();
                System.out.println("当前客户端的IP:" + address.getHostAddress());
                System.out.println("当前本地的IP:" + socket.getLocalSocketAddress());
                System.out.println("当前本地的IP:" + socket.getLocalAddress());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

创建服务端Client读写线程

import java.io.*;
import java.net.Socket;

/**
 * Created by ejiang on 2017-06-20.
 */
public class ServerSocketThread extends Thread {
    //和本线程相关的socket
    Socket socket = null;
    //线程执行的操作,响应客户端的请求
    DataOutputStream dataOutputStream;
    DataInputStream dataInputStream;

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

    @Override
    public void run() {

        try {
            //获取输出流,响应客户端的请求
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            String serverPush = "你说你说socket";
            String length = serverPush.length() + "";
            byte[] intToBytes = length.getBytes("UTF-8");
            byte[] serverPushBytes = serverPush.getBytes("UTF-8");
            dataOutputStream.write(intToBytes);
            dataOutputStream.write(serverPushBytes);
            dataOutputStream.flush();
            socket.shutdownOutput();
            //获取输入流,并读取客户端信息
            dataInputStream = new DataInputStream(socket.getInputStream());
            /**
             * 读取客户端信息:
             */

            int toInt = dataInputStream.readInt();
            switch (toInt) {
                case 0: //文件流
                    //获取文件名称
                    String fileName = dataInputStream.readUTF();
                    System.out.println(fileName);
                    //获取文件长度
                    long readLong = dataInputStream.readLong();
                    System.out.println(readLong);
                    //获取文件输入流
                    File file = new File("D:/input/" + fileName);
                    if(file.exists()){
                        file.delete();
                    }else{
                        file.createNewFile();
                    }

                    FileOutputStream   fos = new FileOutputStream(file);
                    // 开始接收文件
                    byte[] bytes = new byte[1024];
                    int num = 0;
                    while((num = dataInputStream.read(bytes, 0, bytes.length)) != -1) {
                        fos.write(bytes, 0, num);
                        fos.flush();
                    }
                    break;
                case 1: //string字符流
                    break;
                case 2:
                    break;
            }
            socket.shutdownInput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
    原文作者:MrZang
    原文地址: https://www.jianshu.com/p/557c236c810f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞