通过socket来将客户端文件传给服务器端

上一篇为大家介绍了利用java程序发送post请求来传递文件流,但是却有大小限制,那么我们这次就来写一个socket,通过网络套接字来传递来往于客户端和服务器的文件。

我想大家对于java 的socket编程不会太陌生,那我就直接切入主题,分别编写服务器和客户端代码:

Server:

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { /** * @param args */ public static void main(String[] args) { //ServerSocket server; Long beginTime = null; try { ServerSocket server = new ServerSocket(1234); while (true) { final Socket sk = server.accept(); //通过套接字来发送文本 InputStream inStream = sk.getInputStream(); OutputStream outStream = sk.getOutputStream(); Scanner in = new Scanner(inStream); PrintWriter out = new PrintWriter(outStream, true); out.println("the program is beginning:"); boolean done = false; while (!done && in.hasNextLine()) { String line = in.nextLine(); out.println("Echo" + line); if (line.trim().equals("bye")) { done = true; } } sk.close(); /*new Thread(new Runnable() { @Override public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream())); //System.out.println(br.readLine()); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start();*/ } } catch (IOException e) { System.out.println("fail"); e.printStackTrace(); } } }

Client:

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; public class Client { /** * @param args */ public static void main(String[] args) { // 创建套接字 Socket sk; PrintStream ps; //Temp temp = Temp.getInstance(); //temp.setSEND_TIME(System.currentTimeMillis()); //Long beginTime = temp.getSEND_TIME(); //System.out.println(beginTime); try { sk = new Socket("localhost", 1234); ps = new PrintStream(sk.getOutputStream()); //读取文件 File file = new File("E:/toodou_work/testSmall.csv"); BufferedReader br = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); String str = null; while ((str = br.readLine()) != null) { sb.append(str); } String content = sb.toString(); ps.print(content); sk.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { System.out.println("link to server is fail"); e.printStackTrace(); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值