本帖最后由 FFF 于 2013-11-14 21:02 编辑
import java.io.*;
import java.net.*;
class picClient
{
public static void main(String[] args) throws Exception
{
if(args.length!=1)
{
System.out.println("请选择一个jpg格式的图片");
return ;
}
File file = new File(args[0]);
if(!(file.exists() && file.isFile()))
{
System.out.println("该文件有问题,要么不存在,要么不是文件");
return ;
}
if(!file.getName().endsWith(".jpg"))
{
System.out.println("图片格式错误,请重新选择");
}
if(file.length()>1024*1024*4)
{
System.out.println("文件过大");
return ;
}
Socket s = new Socket("192.168.1.100",10007);
BufferedInputStream bur = new BufferedInputStream(new FileInputStream(file));
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len=bur.read(buf))!=-1)
{
out.write(buf,0,len);
}
//告诉服务端已经写完
s.shutdownOutput();
InputStream in = s.getInputStream();
byte[] buIn=new byte[1024];
int num = in.read(buIn);
System.out.println(new String(buf,0,num));
bur.close();
s.close();
}
}
class threadPic implements Runnable
{
private Socket s;
threadPic(Socket s)
{
this.s = s;
}
public void run()
{
try
{
int count = 1;
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....conection");
InputStream in = s.getInputStream();
File file = new File(ip+"("+(count++)+")"+".jpg");
while(file.exists())
file = new File(ip+"("+(count++)+")"+".jpg");
FileOutputStream out = new FileOutputStream(file);
byte[] buIn = new byte[1024];
int num = 0;
while((num=in.read(buIn))!=-1)
{
out.write(buIn,0,num);
}
OutputStream os = s.getOutputStream();
os.write("上传成功".getBytes());
out.close();
s.close();
}
catch (Exception e)
{
throw new RuntimeException("上传失败");
}
}
}
class picServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10007);
while(true)
{
Socket s = ss.accept();
new Thread(new threadPic(s)).start();
}
}
} |