本文实现了多客户端共同上传文件的功能,当然还少一些图形界面。所以只是介绍一下原理
import java.net.*;
import java.text.*;
import java.io.*;
import java.util.*;
public class UploadPic {
public static void main(String[] args) {
// TODO 自动生成的方法存根
}
}
class picServer{
public static void main(String[] args) throws Exception{
ServerSocket ss=new ServerSocket(10009);
while(true){
Socket s=ss.accept();
//根据这句话,实现了多线程,客户端发一个请求就可以实现新建立一个线程与其通讯
new Thread(new PicThread(s)).start();
}
}
}
class PicThread implements Runnable{
private Socket s;
PicThread(Socket s){
this.s=s;
}
public void run(){
String ip=s.getInetAddress().getHostAddress();
int port=s.getPort();
try {
File dir=new File("D:\\workspace");
String ly_time = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(Calendar.getInstance().getTime());
File file=new File(dir,ip+"-"+port+"("+ly_time+").jpg");
//System.out.println(ly_time);
//File file=new File(dir,ip+".jpg");
InputStream in=s.getInputStream();//获取socket客户端发送过来的数据
OutputStream out=s.getOutputStream();//将要传输的数据放入socket管道上
FileOutputStream fos=new FileOutputStream(file); //将客户端的数据写入服务器端 用fos转换写入
byte[] buf=new byte[1024*4];
int len=0;
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
String returnString=ip+"上传成功!";
out.write(returnString.getBytes());
fos.close();
s.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
throw new RuntimeException(ip+"------客户端未能连接上!");
}
}
}
class PicClient{
public static void main(String[] args) throws Exception, Exception{
File file = new File("psb.jpg"); //可以做一个图形界面选择文件 也可以通过main函数传输
if(!(file.exists() && file.isFile()))
{
System.out.println("文件错误");
return;
}
if(!(file.getName().toLowerCase().endsWith(".jpg")))
{
System.out.println("必须是jpg的文件");
return ;
}
if(file.length()>1024*1024*4)
{
System.out.println("文件过大");
return;
}
//连接服务端
Socket s=new Socket("192.168.0.133",10009);
//写入outputStream流,发送到服务端
OutputStream out=s.getOutputStream();
FileInputStream fis=new FileInputStream(file);
byte[] buf = new byte[1024*4];
int len = 0;
while((len=fis.read(buf))!=-1)
{
out.write(buf,0,len); //写入管道
}
s.shutdownOutput(); //提示写入完毕
//接收服务器反馈信息
InputStream in=s.getInputStream();
byte[] bufIn = new byte[1024];
int lenIn = in.read(bufIn);
String str = new String(bufIn,0,lenIn);
System.out.println("server:"+str);
fis.close();
s.close();
}
}