服务器端启动

package com.qianfeng.tcp4;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadServer {

    /**
     * 实现文本文件的上传的服务端
     * 1:接收客户端发送过来的数据
     * 2:写入到服务器端的某个文件
     * 3:发送"上传成功"
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        System.out.println("服务器端启动...");
        ServerSocket server = new ServerSocket(24444);
        
        Socket socket = server.accept();
        System.out.println(socket.getInetAddress().getHostAddress()+"连接到服务器.....");
        
        //接收客户端发送过来的数据
        InputStream in = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        
        //写入到服务器端的某个文件
        PrintWriter pw = new PrintWriter(new FileWriter("files\\Demo1_copy.java"),true);
        
        //发送"上传成功"
        OutputStream out = socket.getOutputStream();
        PrintWriter pww = new PrintWriter(out,true);
        
        //循环读取客户端数据写入到本地文件
        String line = null;
        while((line=br.readLine())!=null)//读不到null
        {
            pw.println(line);
        }
        pw.close();
        //发送"上传成功"
        pww.println("上传成功");
        
        socket.close();
        
        
    }

}

 

posted @ 2017-08-20 10:50  又等风来  阅读(169)  评论(0编辑  收藏  举报