黑馬程序員—TCP-客戶端併發上傳圖片小例子

------- <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>、期待與您交流! ----------



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章