//毕老师讲的网络传递jpg图片例子
import java.io.*;
import java.net.*;
class PicClient
{
public static void main(String[] args)throws Exception
{
if(args.length!=1)//arge这个数组不就是主函数的默认数组吗?默认的不是为空的吗
{ //既然是空的怎么能参与判断呢?好像没什么意义啊
System.out.println("请选择一个jpg格式的图片");
return ;
}
File file = new File(args[0]); //还是这个数组,第一个应该是空的啊,怎么下面我打印的时候会有值呢?
//他又怎么能封装成文件呢
if(!(file.exists() && file.isFile()))//到这步有没有什么东西传过来怎么判断所谓的文件
{
System.out.println(args[0] );
System.out.println("该文件有问题,要么补存在,要么不是文件");
return ;
}
if(!file.getName().endsWith(".jpg"))
{
System.out.println("图片格式错误,请重新选择");
return ;
}
Socket s = new Socket("192.168.1.98",10007);
FileInputStream fis = new FileInputStream(file);
OutputStream out = s.getOutputStream();//s这个套接字得到的是什么输出字节流
byte[] buf = new byte[1024];
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 num = in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
class PicThread implements Runnable
{
private Socket s;
PicThread(Socket s)
{
this.s = s;
}
public void run()
{
int count = 1;
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");
InputStream in = s.getInputStream();
File dir = new File("d:\\pic");
File file = new File(dir,ip+"("+(count)+")"+".jpg");
while(file.exists())
file = new File(dir,ip+"("+(count++)+")"+".jpg");
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))!=-1)
{
fos.write(buf,0,len);
}
OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
s.close();
}
}
class PicServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10007);
while(true)
{
Socket s = ss.accept();//ss服务端套接字得到连接为什么有赋给s客户端套接字呢
new Thread(new PicThread(s)).start();
}
}
}
//这几个小问题困扰我很久,请高手指教
|