使用Socket和ServerSocket上传文件

原创
2017/06/28 16:15
阅读数 72

一,编写Sever端代码

package com.pengda.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadServer {
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(5678) ;
			Socket socket = serverSocket.accept() ;		//阻塞状态,等待client请求
			//输入流字节流
			InputStream is = socket.getInputStream() ;
			//将字节流放入缓冲
			BufferedInputStream bis = new BufferedInputStream(is) ;
			//
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\copy.jpg")) ;
			
			byte[] b = new byte[1024] ;
			int len = 0 ;
			while((len=bis.read(b))>0){
				bos.write(b, 0, len) ;
				System.out.println(len) ;
			}
			OutputStream os = socket.getOutputStream() ;
			PrintWriter pw = new PrintWriter(os) ;
			pw.write("上传 成功");
			pw.flush() ;
			
			os.close() ;
			bos.close();
			bis.close();
			is.close();
			socket.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

二,编写Client端代码

package com.pengda.socket;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class UploadClient {
	public static void main(String[] args) {
		String path = "D:\\1.jpg" ;
		try {
			Socket socket = new Socket("localhost",5678) ;
			
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path)) ;
			OutputStream os = socket.getOutputStream() ;
			
			byte[] b = new  byte[1024] ;
			int len = 0 ;
			while((len=bis.read(b))>0){
				os.write(b, 0, len) ;
			}
			socket.shutdownOutput() ;
			System.out.println("关闭输出流") ;
			
			InputStream is = socket.getInputStream() ;	//字节流
			InputStreamReader isr = new InputStreamReader(is) ;	//字节流转为 字符流
			BufferedReader br = new BufferedReader(isr) ;
			String info = null ;
			while((info=br.readLine())!=null){
				System.out.println("服务器端返回的数据:"+info) ;
			}
			socket.shutdownInput() ;
			
			os.close();
			bis.close() ;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部