客户与服务器之文件传送

04-03-08 pzliang16
服务器

import java.io.*;

import java.net.*;

public class Server implements Runnable{

private Socket socket;

private int ID;

Server(Socket socket,int ID){

this.socket=socket;

this.ID=ID;

}

public static void main(String[] args){

int port=9999;

int count=0;

try{

ServerSocket s=new ServerSocket(port);

System.out.println(" 正在等待端口 "+port);

while(true){

Socket socket=s.accept();

System.out.println("第"+ ++count+"台电脑已经获得连接!!!");

Server server=new Server(socket,count);

Thread thread=new Thread(server);

thread.start();

}

}

catch(Exception e){

System.out.print("错误!!");

}

}

public void run(){

try{

InputStream is=socket.getInputStream();

InputStreamReader isr=new InputStreamReader(is);

BufferedReader br=new BufferedReader(isr);

FileOutputStream fos=new FileOutputStream(new File("aa.txt"));

String str=br.readLine();

byte[] b=new byte[1024];

b=str.getBytes();

fos.write(b);

}

catch(Exception e){

System.out.println(e.toString());

}

finally{

try{

socket.close();

System.out.println(ID+"已经断开了!!!");

}

catch(Exception e){

System.out.print("最后有错误!!");

}

}

}

}

*********************

客户

import java.io.*;

import java.net.*;

public class Client{

public static void main(String[] args){

int port=9999;

try{

InetAddress address=InetAddress.getByName("192.168.0.1");

Socket socket=new Socket(address,port);

String file=args[0];

FileInputStream fips=new FileInputStream(file);

BufferedInputStream bis=new BufferedInputStream(fips);

DataInputStream in=new DataInputStream(bis);

BufferedReader br=new BufferedReader(new InputStreamReader(in));

OutputStream os=socket.getOutputStream();

OutputStreamWriter osw=new OutputStreamWriter(os);

PrintWriter pw=new PrintWriter(osw);

pw.print(br.readLine());

pw.flush();

}

catch(Exception e){

System.out.println(e.toString());

}

}

}

############

我想请教一下,我的目的是用Client这个程序,将一个文件通过网络,发送到Server这个程序上,然后由Server这个程序把数据写到一个自命名的文件上。

请高手指教!!!谢谢!!

猜你喜欢