用UDP协议实现文件传输
是课堂的作业,必须用UDP协议实现文件传输,不需要GUI实现,控制台就好~我是小菜鸟,刚入门,写了如下两个UDPServer.java和UDPClient.java,前者错误在socket.close();后者错误在os.close(); 不知道为什么错了,编译不过,所以也不知道自己写的对不对,请各位帮忙修改!感谢!
import java.net.*;
import java.io.*;
import java.lang.*;
public class UDPServer{
public static void main(String args[]){
DatagramSocket socket=null;
DatagramPacket packet=null;
InetAddress address=null;//用来存放接收方的地址
DataInputStream in=null;
int port=0;//用来存放接收方的端口号
try
{
socket=new DatagramSocket(8888);
in=new DataInputStream(new FileInputStream("e:\\text.txt"));
while(true)
{
byte[] buf=new byte[256];//存放从客户端接收的请求信息
packet=new DatagramPacket(buf,buf.length);//用来从socket接收数据
socket.receive(packet);//在客户的请求报到来之前一直等待
byte b[]=new byte[1];
address=packet.getAddress();//从到来的包中得到地址
port=packet.getPort();//从到来的包中得到端口号
packet=new DatagramPacket(b,b.length,address,port);//建立报文包,用来从socket上发送信息
socket.send(packet);//发送数据包
}//while
socket.close();
} catch(Exception e){
System.out.println("Error:"+e);
} //catch
} //main
} //public class
import java.net.*;
import java.io.*;
import java.lang.*;
public class UDPClient{
public static void main(String args[]){
if (args.length<1){
System.out.println("Please input the Server Address and Port!");
System.out.println("see also: localhost 8888");
System.exit(1);
}
DatagramSocket socket=null;
DataOutputStream os=null;
int port=0;
InetAddress address=null;
DatagramPacket packet=null;
byte[] sendBuf=new byte[256];
try{
while(true){
socket=new DatagramSocket();//建立socket
os=new DataOutputStream(new FileOutputStream("e:\\text.txt"));
address=InetAddress.getByName(args[0]);
port=Integer.parseInt(args[1]);
packet=new DatagramPacket(sendBuf,sendBuf.length,address,port);
socket.send(packet);//向服务器发出请求报文
packet=new DatagramPacket(sendBuf,sendBuf.length);
socket.receive(packet);//客户机等待应带,若没有就一直等待
String received=new String(packet.getData(),0);
System.out.println(received);//处理接收到的数据
}//while
os.close();
socket.close();
}catch(Exception e){
System.out.println("Error:"+e);
} //catch
}//main
}//public class