實(shí)現(xiàn)思路:
在客戶端獲取到文件流,將文件流寫入到通過socket指定到某服務(wù)器的輸出流中,在服務(wù)器中通過socket獲取到輸入流,將數(shù)據(jù)寫入到指定的文件夾內(nèi),為了提供多用戶同時(shí)上傳,這里需要將在服務(wù)器上傳客戶端的文件操作放在另開啟一個(gè)線程去運(yùn)行。
完整代碼:
view plain
import java.net.*;
import java.io.*;
/*
服務(wù)端將獲取到的客戶端封裝到單獨(dú)的線程中。
*/
class JpgClient2
{
public static void main(String[] args) throws Exception
{
//檢驗(yàn)文件
if(args.length==0)
{
System.out.println("指定一個(gè)jpg文件先!");
return ;
}
File file = new File(args[0]);
if(!(file.exists() && file.isFile() && file.getName().endsWith(".jpg")))
{
System.out.println("選擇文件錯(cuò)誤,請(qǐng)重新選擇一個(gè)正確的文件。");
return ;
}
//讀取文件并寫入到服務(wù)器中
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);
}
//通知服務(wù)器發(fā)送數(shù)據(jù)結(jié)束
s.shutdownOutput();
//獲取服務(wù)器響應(yīng)
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
{
//獲取客戶端數(shù)據(jù)
InputStream in = s.getInputStream();
//指定文件存放路徑將讀取到客戶提交的數(shù)據(jù)寫入文件中
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);
}
//返回上傳狀態(tài)給客戶端
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);
//開啟線程并發(fā)訪問
while(true)
{
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");
new Thread(new JpgThread(s)).start();
}
}
}