黑马程序员技术交流社区
标题:
复习tcp上传图片的代码,多线程处理socket问题请教
[打印本页]
作者:
木易在他乡
时间:
2014-8-26 13:13
标题:
复习tcp上传图片的代码,多线程处理socket问题请教
本帖最后由 木易在他乡 于 2014-8-26 13:17 编辑
请看下面PicServer代码中相关问题及其出处。
import java.io.*;
import java.net.*;
class PicClinet
{// 1,此处为什么要调用主函数来传图片?正常情况下应该如何写比较好?
public static void main(String[] args) throws Exception
{
if(args.length!=-1){
System.out.println("选择一个图片");
return;
}
File file=new File(args[0]);
if(!file.exists()&&file.isFile()){
System.out.println("不存在或不是文件");
}
if(!file.getName().endsWith(".jpg")){
System.out.println("格式错误");
}
Socket s=new Socket("127.0.0.1",10007);
FileInputStream fis=new FileInputStream(file);
OutputStream out=s.getOutputStream();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
class PicServer
{
public static void main(String[] args)
{
ServerSocket ss=new ServerSocket(10007);
while(true){
Socket s=ss.accept();
//此处为每一个socket通信都单独创建一个线程,问:1,能不能采用一个线程依次执行各个socket请求?如何写?2,多线程在此有没有同步安全问题?
new Thread(new PicThread(s)).start();
}
ss.close();
}
}
class PicThread implements Runnable
{
private Socket s;
PicThread(Socket s){ this.s=s;}
public void run(){
int count=0;
String ip=s.getInetAddress().getHostAddress();
try{
System.out.println(ip+"...");
InputStream in=s.getInputStream();
File file=new File(ip+"("+(count)+").jpg");
while(file.exists()){
file=new File(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();
}
catch(Exception e){
throw new RuntimeException(ip+"上传失败");
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2