码迷,mamicode.com
首页 > 编程语言 > 详细

java TCP上传文本

时间:2015-07-17 09:56:52      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

服务端:

   

package cn.net.tcp;

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 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();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip + "...connected");
		BufferedReader bufr = new BufferedReader(new InputStreamReader(
				s.getInputStream()));

		PrintWriter pw = new PrintWriter(new FileWriter("server.txt"), true);
		String line = null;
		while ((line = bufr.readLine()) != null) {
			pw.println(line);
		}

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

	}

}

客户端:

package cn.net.tcp;

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

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public static void main(String[] args) throws UnknownHostException,
			IOException {
		/*
		 * 上传文本的客户端,读取本地文本数据,发送给服务端,服务端接收完毕后,回馈“上传成功”字样。
		 */

		System.out.println("客户端启动了...");
		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 linIn = bufIn.readLine();
		System.out.println(linIn);
		bufIn.close();
		s.close();
	}

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

java TCP上传文本

标签:

原文地址:http://blog.csdn.net/treeling_/article/details/46918689

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