我有一個使用java的套接字編程項目。我們必須編寫客戶端和服務器代碼來傳輸一個文件,代碼在編譯時沒有顯示錯誤,但是沒有執行,當我放置文件名時它會凍結。如何在Java中使用UDP發送文件
我知道,UDP不是用於發送文件是個好主意,但我必須這樣做的一個項目,我的代碼是:
客戶端代碼
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
static InetAddress dest;
public static void main(String [] args) throws Exception
{
DatagramSocket clskt = new DatagramSocket();
Scanner input = new Scanner (System.in);
int port =input.nextInt();
System.out.println("Enter Destination Host name");
String hostname=input.next();
dest.getByName(hostname);
int packetcount=0;
System.out.println("Enter The path of the file you want to send");
String path = input.next();
File initialFile = new File(path);
FileInputStream targetStream = new FileInputStream(initialFile);
int filesize=targetStream.available();
//int neededpackets =(int)Math.ceil((double)(size/1024));
byte [] data= new byte[1024];
// counting bytes
for (int i=0;i<1024;i++)
{
data[i]=(byte)targetStream.read();
}
//create a packet
DatagramPacket clpkt=new DatagramPacket(data,data.length,dest,port);
packetcount++;
clskt.send(clpkt);
if(packetcount >neededpackets)
clskt.close();
}
}
服務器代碼
import java.io.*;
import java.net.*;
import java.util.*;
class Server1
{
public static void main(String args[])throws Exception
{
System.out.println("Enter Port number !!!");
Scanner input = new Scanner(System.in);
int SPort = input.nextInt();
DatagramSocket srvskt = new DatagramSocket(SPort);
byte[] data =new byte[1024];
System.out.println("Enter a full file name to save data to it ?");
String path = input.next();
System.out.println("file : "+path+" will be created.");
FileOutputStream FOS = new FileOutputStream(path);
DatagramPacket srvpkt = new DatagramPacket(data,1024);
System.out.println("listening to Port: "+SPort);
int Packetcounter=0;//packet counter
while(true)
{
srvskt.receive(srvpkt);
Packetcounter++;
String words = new String(srvpkt.getData());
InetAddress ip= srvpkt.getAddress();
int port = srvpkt.getPort();
System.out.println("Packet # :"+Packetcounter+"
Received from Host/Port: "+ip+"/"+port);
FOS.write(data);
//out16.flush();
if (Packetcounter >=100)
break;
}
FOS.close();//releasing file.
System.out.println("Data has been written to the file !");
}
}
預先感謝所有人。
不要通過UDP發送文件,也不能保證你的數據包將到達,從而破壞你的文件 – redFIVE
我知道,但我必須完成此代碼作爲作業 –
添加'System.out'行「到處」到看看執行實際停止的地方。 – Kayaman