码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程 TCP学习

时间:2014-07-26 02:19:06      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:java   os   数据   io   re   c   html   ar   

上传txt文本 通过socket向服务端发送数据 然后用serversocket 接收socket 通过流读取数据保存 服务端在发送确认信息并在客户端输出

 

客户端

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 txtClient {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub

		Socket s = new Socket("10.64.130.51", 10002);
		
		BufferedReader br =
			new BufferedReader(new FileReader("F:\\fd.txt"));
		
		PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
		
		String str = null;
		
		
		while((str = br.readLine()) != null){
			//System.out.println(str);
			pw.println(str);
		}
		pw.println("over");
		System.out.println("开始上传");
		BufferedReader brin = 
			new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		str = brin.readLine();
		System.out.println(str);
		br.close();
		s.close();
	}
	
}


 

服务端

import java.io.*;
import java.net.*;


public class txtServer {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		ServerSocket ss = new ServerSocket(10002);
		
		Socket s = ss.accept();
		
		BufferedReader brin=
			new BufferedReader(new InputStreamReader(s.getInputStream()));
		
		BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\fd2.txt"));
		
		String str = null;
		
		System.out.println("接受中");
		while((str = brin.readLine()) != null){
			
			System.out.println(str);
			if(str.compareTo("over") == 0)
				break;
			bw.write(str);
		}
		//BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
		pw.println("上传成功");
		bw.close();
		s.close();
		ss.close();
	}

}


 

网络编程 TCP学习,布布扣,bubuko.com

网络编程 TCP学习

标签:java   os   数据   io   re   c   html   ar   

原文地址:http://blog.csdn.net/u011686226/article/details/38124909

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!