java网络编程--socket上传文件

来源:互联网 发布:java游戏开发技术 编辑:程序博客网 时间:2024/04/30 18:36

直接代码不多说!

服务端:

package scoket.file.server;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.*;;public class FileServer {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry {ServerSocket server = new ServerSocket(8888);Socket socket = new Socket();while(true){socket = server.accept();InputStream is =  socket.getInputStream();OutputStream os = socket.getOutputStream();byte[] b = new byte[1024];//1、得到文件名int a = is.read(b);String filename = new String(b, 0, a);System.out.println("接受到的文件名为:"+filename);String houzhui = filename.substring(filename.indexOf("."), filename.length());String rand = String.valueOf((int) (Math.random() * 100000));filename = rand+houzhui;System.out.println("新生成的文件名为:"+filename);FileOutputStream fos = new FileOutputStream("f:\\"+filename);int length = 0;while((length=is.read(b))!=-1){//2、把socket输入流写到文件输出流中去fos.write(b, 0, length);}//fos.flush();fos.close();os.flush();os.close();is.close();socket.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}


客户端

package scoket.file.client;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class FileCilent {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry {Socket client = new Socket("192.168.3.28", 8888);InputStream is =  client.getInputStream();OutputStream os = client.getOutputStream();String filepath="e:\\MyServer.java";File file = new File(filepath);String filename = file.getName();System.out.println("send's file name:"+filename);//1、发送文件名os.write(filename.getBytes());FileInputStream fis = new FileInputStream(file);byte[] b = new byte[1024];int length = 0;while((length=fis.read(b))!=-1){//2、把文件写入socket输出流os.write(b, 0, length);}os.close();fis.close();is.close();System.out.println("send over");} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


 

原创粉丝点击