黑马程序员—TCP-客户端并发上传图片小例子

来源:互联网 发布:黑马程序员java培训 编辑:程序博客网 时间:2024/04/28 11:29

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

写着两个程序是我是卸载两个java文件下的,而且这两个文件分别放在了两个不同的目录下,也就是同时打开两个MyEclipse窗口,这样有利于调试,查看效果更明显。

客户端:

package twenty_four;
import java.io.*;
import java.net.*;
import java.util.*;
public class PicClient2 {
public static void main(String[] args)throws Exception {
/*if(args.length!=1)
{
System.out.println("请选择一个JPG格式端图片");//选择Run->Run Configurations->选择Arguments选项卡,将需要上传的图片及路径放到Program aguments中,运行就OK了
return;
}*/
Scanner sc = new Scanner(System.in);
         System.out.println("请选择一个JPG格式端图片:");
         String str = sc.nextLine();
         sc.close();
//File file=new File(args[0]);
         File file=new File(str); 
if(!(file.exists()&&file.isFile()))
{
System.out.println("文件有问题");
}
if(!file.getName().endsWith(".jpg"))
{
System.out.println("图片格式错误");
return;
}
if(file.length()>1024*1024*5)
{
System.out.println("文件过大");
return;
}
Socket s=new Socket("192.168.106.88",40007);
FileInputStream fis=new FileInputStream(file);
OutputStream out =s.getOutputStream();
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();
}
}

服务端:

package twenty_four;
import java.io.*;
import java.net.*;
/*服务端
这个服务端有个局限性,当客户端连接上以后。被服务端获去到
这是B客户端连接,只有等待。
因为福无端还没有处理完A客户端请求还有循环回来执行下次accept
方法,所以暂时获取不到B客户端端对象。
那么为了让多个客户端同时并发访问服务端。
那么服务端最好就是讲每个客户端封装到一个单独端线程中,这样就可以同事处理
多个客户端。*/
//定义线程
//只要明确了每一个客户端要在服务端执行的代码即可,将该方法存入Run方法中。
class PicThread implements Runnable
{
private Socket s;
PicThread( Socket s)
{
this.s=s;
}
public void run()
{ int count=1;
String ip=s.getInetAddress().getHostAddress();
try{

System.out.println(ip+"...........connection");
InputStream in=s.getInputStream();
File file=new File(ip+"("+(count)+")"+".jpg");
while(file.exists())
file=new File(ip+"("+(count)+")"+".jsp");
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+"上传失败");
}


}
}
public class PicServer2 {
public static void main(String[] args) throws Exception{
ServerSocket ss=new ServerSocket(40007);
while(true)
{
Socket s=ss.accept();
new Thread(new PicThread(s)).start();
}
}


}

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------



0 0