服務器端:
package tcp;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Fileserver implements Runnable {
private static final int port=8000;//服務器監聽端口
private Socket s;
public Fileserver(Socket s){
super();
this.s=s;
}
public static void server(){
try{
ServerSocket ss=new ServerSocket(port);//建立服務器Socket
while(true){
Socket s=ss.accept();
new Thread(new Fileserver(s)).start();//將聯通的socket傳給該線程
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
Fileserver.server();
}
public void run() {
byte[] buf=new byte[100];
OutputStream os=null;
FileInputStream fins=null;
try{
os=s.getOutputStream();
String filepath="F:\\java高級
\\network\\file.txt";
String filename="file.txt";
System.out.println("將文件名:"+filename+"傳輸過去");
os.write(filename.getBytes());
System.out.println("開始傳輸文件");
fins=new FileInputStream(filepath);
int data;
while((data=fins.read())!=-1)
{
os.write(data);
}
System.out.println("文件傳輸結束");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(fins!=null)
fins.close();
if(os!=null)
os.close();
this.s.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
客戶端:
package tcp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class Fileclient {
private static final String serverip="127.0.0.1";
private static final int sport=8000;
private static final int cport=8001;
public static void main(String[] args) {
byte[] buf=new byte[100];//用來接收傳過來的字符
Socket s=new Socket();
try{
s.connect(new InetSocketAddress(serverip,sport),cport);
InputStream is=s.getInputStream();
int len=is.read(buf);
String filename=new String(buf,0,len);
System.out.println(filename);;
FileOutputStream fos=new FileOutputStream("F:\\java高級
\\"+filename);
int data;
while((data=is.read())!=-1)
{
fos.write(data);
}
is.close();
s.close();
}catch(IOException e){
e.printStackTrace();
}
}
}