實現思路:
在用戶端擷取到檔案流,將檔案流寫入到通過socket指定到某伺服器的輸出資料流中,在伺服器中通過socket擷取到輸入資料流,將資料寫入到指定的檔案夾內,為了提供多使用者同時上傳,這裡需要將在伺服器上傳用戶端的檔案操作放在另開啟一個線程去運行。
完整代碼:
view plain
import java.net.*;
import java.io.*;
/*
服務端將擷取到的用戶端封裝到單獨的線程中。
*/
class JpgClient2
{
public static void main(String[] args) throws Exception
{
//檢驗檔案
if(args.length==0)
{
System.out.println("指定一個jpg檔案先!");
return ;
}
File file = new File(args[0]);
if(!(file.exists() && file.isFile() && file.getName().endsWith(".jpg")))
{
System.out.println("選擇檔案錯誤,請重新選擇一個正確的檔案。");
return ;
}
//讀取檔案並寫入到伺服器中
Socket s = new Socket("192.168.137.199",9006);
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);
String str = new String(bufIn,0,num);
System.out.println(str);
fis.close();
s.close();
}
}
class JpgThread implements Runnable
{
private Socket s;
JpgThread(Socket s)
{
this.s = s;
}
public void run()
{
int count = 1;
String ip = s.getInetAddress().getHostAddress();
try
{
//擷取用戶端資料
InputStream in = s.getInputStream();
//指定檔案存放路徑將讀取到客戶提交的資料寫入檔案中
File dir = new File("c:\\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();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
}
class JpgServer2
{
public static void main(String[] args)throws Exception
{
ServerSocket ss = new ServerSocket(9006);
//開啟線程並發訪問
while(true)
{
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");
new Thread(new JpgThread(s)).start();
}
}
}