继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

tcp版文件上传

慕田峪9129951
关注TA
已关注
手记 337
粉丝 200
获赞 993

客户端

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.IOException;import java.io.OutputStreamWriter;import java.net.InetAddress;import java.net.Socket;import java.net.SocketException;import java.net.UnknownHostException;/** *  * @author WangShuang * */public class ClientDemo {    public static void main(String[] args) throws SocketException {        Socket socket = null;        BufferedReader br =null;        try {            InetAddress byName = InetAddress.getByName("192.168.1.102");            //创建客户端socket服务,指定目的主机和端口             socket = new Socket(byName,9999);            //为了发送数据,应该获取socket流中的输出流,将数据写到该流中,通过网络发送给服务端            BufferedWriter bwsocket = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));            //将硬盘中的文件读取到流中            br = new BufferedReader(new FileReader("c:\\文件上传.txt"));            String  readLine = null;            while((readLine=br.readLine())!=null){                bwsocket.write(readLine);                bwsocket.newLine();                bwsocket.flush();            }        } catch (UnknownHostException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            try {                br.close();                //关闭客户端资源                socket.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

}

服务端

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class ServiceDemo {    public static void main(String[] args) {        //创建服务端socket服务        ServerSocket serverSocket=null;        Socket socket =null;        BufferedWriter bw =null;        try {            serverSocket = new ServerSocket(9999);            //获取客户端socket对象            socket = serverSocket.accept();            BufferedReader brsocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));            bw = new BufferedWriter(new FileWriter("d:\\文件上传.txt"));            String readLine=null;            while ((readLine=brsocket.readLine())!=null) {                bw.write(readLine);            }        } catch (IOException e) {            e.printStackTrace();        }finally {            try {                bw.close();                socket.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP