首页 > 其他 > 详细

模拟上传服务端

时间:2014-04-23 17:17:43      阅读:459      评论:0      收藏:0      [点我收藏+]

从客户端上传文本文件到服务端,用到了Socket流,服务端接收完毕后,返回给客户端。(希望得到大家批评指正)bubuko.com,布布扣bubuko.com,布布扣

客户端:

bubuko.com,布布扣
UploadClient.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class UploadClient {

    /**
     * @param args
     * @throws IOException
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws UnknownHostException,
            IOException {

        Socket s = new Socket("127.0.0.1", 10005);

        BufferedReader bufr = new BufferedReader(new FileReader("client.txt"));

        PrintWriter out = new PrintWriter(s.getOutputStream(), true);

        String line = null;
        while ((line = bufr.readLine()) != null) {
            out.println(line);
        }

        s.shutdownOutput();
        // 获取服务端信息
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(
                s.getInputStream()));

        String str = bufIn.readLine();
        System.out.println(str);

        bufr.close();
        s.close();

    }

}
bubuko.com,布布扣

服务端:

bubuko.com,布布扣
UploadServer.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadServer {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        System.out.println("上传服务端....");

        ServerSocket ss = new ServerSocket(10005);

        Socket s = ss.accept();

        System.out.println(ss.getInetAddress().getHostAddress()
                + "....connection");

        BufferedReader bufIn = new BufferedReader(new InputStreamReader(
                s.getInputStream()));

        BufferedWriter bufw = new BufferedWriter(new FileWriter("server.txt"));

        String line = null;
        while ((line = bufIn.readLine()) != null) {
            bufw.write(line);
            bufw.newLine();
            bufw.flush();

        }

        PrintWriter out = new PrintWriter(s.getOutputStream(), true);
        out.println("上传成功");

        bufw.close();
        s.close();
        ss.close();

    }

}
bubuko.com,布布扣

模拟上传服务端,布布扣,bubuko.com

模拟上传服务端

原文:http://www.cnblogs.com/stonewu/p/3682627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!