波神

导航

java socket之上传文件

一、功能介绍

该功能主要实现,将客户端的:F:/work/socketSample/filetemp/client/test_client.txt上传到服务端F:/work/socketSample/filetemp/server/test_server.txt,并将test_client.txt名字修改为test_server.txt,如果服务端收到文件,则向客户端发送提示信息”文件已保存至服务器的F:/work/socketSample/filetemp/server/test_server.txt“

二、工程目录结构

三、服务端

1)Server,服务端主类,监听端口,有请求将开启处理子线程

package fileSockeServer;

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

/**
 * 基于TCP协议的Socket通信,实现文件传输-服务器端
 */
public class Server {
    public static void main(String[] args) {
    try {
        // 创建一个服务器端的ServerSocket,绑定并监听9999端口
        ServerSocket serverSocket = new ServerSocket(9999);
        int count = 0;// 记录客户端的数量
        System.out.println("服务器启动,等待客户端的连接。。。");
        Socket socket = null;
        while (true) {
        // 循环监听等待客户端的连接
        socket = serverSocket.accept();
        // 每当一个客户端连接到服务器,服务器启动一个单独的线程处理与此客户端的通信
        ++count;
        Thread serverHandleThread = new Thread(new ServerHandleThread(socket));
        serverHandleThread.setPriority(4);// 设置线程的优先级[1,10],1为最低,默认是5
        serverHandleThread.start();
        System.out.println("上线的客户端有" + count + "个!");
        InetAddress inetAddress = socket.getInetAddress();
        System.out.println("当前客户端的IP地址是:"+ inetAddress.getHostAddress());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}

2)ServerHandleThread,对客户端的请求进行处理的子线程类

package fileSockeServer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerHandleThread implements Runnable{

    Socket socket = null;// 和本线程相关的Socket
    public ServerHandleThread(Socket socket) {
        super();
        this.socket = socket;
    }
    // 响应客户端的请求
    @Override
    public void run() {
        // TODO Auto-generated method stub
        OutputStream os = null;
        PrintWriter pw = null;
        try {
            InputStream is=socket.getInputStream();
            // 要完成客户端文件上传到服务器的功能需要将客户机的文件通过FileInputStream进行读取,并包装成BufferedInputStream,
            //将套接字的输出流包装成BufferedOutputStream,用BufferedInputStream中的read()方法读取文件中的数据,
            //并用 BufferedOutputStream中的write()方法进行写入,这样文件就送入了Socket的输出流;
            BufferedInputStream bufferedInputStream = new BufferedInputStream(is);// 将BufferedInputStream与套接字的输入流进行连接
            BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("F:/work/socketSample/filetemp/server/test_server.txt"));
            byte[] buf=new byte[1024];
            int len=0;
            while((len=bufferedInputStream.read(buf))!=-1){
                bufferedOutputStream.write(buf, 0, len);
            }
            //强行写入输出流,因为有些带缓冲区的输出流要缓冲区满的时候才输出
            bufferedOutputStream.flush();// 刷新缓冲流
            socket.shutdownInput();// 关闭输入流
            os=socket.getOutputStream();
            pw=new PrintWriter(os);
            pw.println("文件已保存至服务器的F:/work/socketSample/filetemp/server/test_server.txt");
            pw.flush();
            socket.shutdownOutput();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            // 关闭相关资源
            try {
            if (pw != null) {
                pw.close();
            }
            if (os != null) {
                os.close();
            }
            if (socket != null) {
                socket.close();
            }
            } catch (IOException e) {
            e.printStackTrace();
            }
        }
        
    }

}

四、客户端

1)Client,向服务端发送文件,如果收到服务的反馈信息,将信息打印输出

package fileSocketClient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 基于TCP协议的Socket通信,实现文件传输-客户端
 */
public class Client {
    public static void main(String[] args) {
    try {
        // 1.创建客户端的Socket,指定服务器的IP和端口
        Socket socket = new Socket("127.0.0.1", 9999);
        // 2.获取该Socket的输出流,用来向服务器发送文件
        OutputStream os = socket.getOutputStream();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);// 将BufferedOutputStream与套接字的输出流进行连接      
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("F:/work/socketSample/filetemp/client/test_client.txt"));// 读取客户机文件
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = bufferedInputStream.read(buf)) != -1) {
            bufferedOutputStream.write(buf, 0, len);// 向BufferedOutputStream中写入数据
        }
        bufferedOutputStream.flush();// 刷新缓冲流
        socket.shutdownOutput();// 禁用此套接字的输出流
        
        // 3.获取输入流,取得服务器的信息
        InputStream is = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String info = null;
        while ((info = br.readLine()) != null) {
         System.out.println("服务器端的信息:" + info);
        }
        socket.shutdownInput();// 禁用此套接字的输出流
        // 4.关闭资源
        os.close();
        bufferedInputStream.close();
        bufferedOutputStream.close();
        is.close();
        br.close();
        socket.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}

 

posted on 2016-09-21 13:24  波神  阅读(4008)  评论(0编辑  收藏  举报