码迷,mamicode.com
首页 > 编程语言 > 详细

Java网络编程 - 客户端向服务器端发送文件的简单实现

时间:2019-10-05 12:51:31      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:soc   tst   system   load   prope   etc   void   exce   服务器   

1、Client

package cn.qi.Client;

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

public class Client {
    Socket clientSocket;
    Client() {
        // 建立连接到服务器端的socket
        try {
            clientSocket = new Socket("127.0.0.1", 5000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readFileAndSent() throws IOException {
        OutputStream os = clientSocket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

        // 读文件
        String path = this.getClass().getClassLoader().getResource("./prop/text.txt").getPath();
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        String str = null;
        while((str = br.readLine()) != null) {
            System.out.println(str);
            // 每读一行,写一行
            bw.write(str);
            // 获取当前OS的换行符并写入
            bw.write(System.getProperty("line.separator"));
            bw.flush();
        }

        // 关闭流
        bw.close();
        br.close();
        fr.close();

        clientSocket.close();
    }
}

 

2、Server

package cn.qi.Server;

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

public class Server {
    ServerSocket serverSocket;
    Server() {
        // 建立severSocket,监听对应端口
        try {
            serverSocket = new ServerSocket(5000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readFileAndWrite() throws IOException {
        // 获取写入路径
        String path = this.getClass().getClassLoader().getResource("./prop/").getPath();
        // 服务器端写文件
        FileWriter fw = new FileWriter(path+"textSocket.txt");
        BufferedWriter bw = new BufferedWriter(fw);

        // 写的内容来自网络端
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = null;
            while((str = br.readLine()) != null) {
                // 读到了客户端发送的信息
                bw.write(str);
                // 获取当前OS的换行符并写入
                bw.write(System.getProperty("line.separator"));
                bw.flush();
            }

            // 关闭流
            br.close();

            socket.close();
        }
    }
}

 

Java网络编程 - 客户端向服务器端发送文件的简单实现

标签:soc   tst   system   load   prope   etc   void   exce   服务器   

原文地址:https://www.cnblogs.com/GjqDream/p/11624327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!