模拟上传服务端

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

客户端:

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();

    }

}

服务端:

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();

    }

}
posted @ 2014-04-23 12:23  .stone_  阅读(171)  评论(0编辑  收藏  举报