首页 > Web开发 > 详细

网络编程-TCP程序实例(上传文件)

时间:2016-01-19 23:35:41      阅读:248      评论:0      收藏:0      [点我收藏+]
package netTest;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
// 发送数据的结束标记...  自定义结束标记,先告诉服务器自己的结束标记。
// 时间戳   socket 方法。。。
public class TextClient {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Socket s = new Socket(InetAddress.getLocalHost(),7899);
        BufferedReader bufr = new BufferedReader(new FileReader("TcpClient.java"));
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        long time = System.currentTimeMillis();
        
        out.println(time);
        String line = null;
        while((line = bufr.readLine())!=null){
            //System.out.println(line);
            out.println(line);
        }
        // 关闭客户端输出流
        s.shutdownOutput();  //关闭输出流,相当于加了一个结束标记-1
        //  自定义结束标记  out.println("over");
        BufferedReader bufIn  = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str = bufIn.readLine();
        System.out.println(str);
        bufr.close();
        s.close();
    }

}


package netTest;

import java.io.BufferedReader;
import java.io.FileReader;
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 TextServer {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        ServerSocket ss = new ServerSocket(7899);
        Socket s = ss.accept();
        System.out.println(s.getInetAddress().getLocalHost()+"...........connected");
        
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter out = new PrintWriter(new FileWriter("server.java"),true);
        String line = null;
        while((line = bufIn.readLine())!=null){
            //System.out.println(line);
            if("over".equals(line)){
                // 自定义结束标记。
                break;
            }
            out.println(line);
        }
        PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
        pw.println("上传成功!!!");
        out.close();
        s.close();
        ss.close();
    }

}

 

网络编程-TCP程序实例(上传文件)

原文:http://www.cnblogs.com/yangyongqian/p/5143578.html

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