正如我的标题中所述,我正在尝试在 java 中构建一个非常简单的文件传输服务。现在,我所能做的就是构建一个可以发送和接收文本字符串的简单客户端/服务器。这是代码:
UDPClient.java:
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader
(System.in));
DatagramSocket clientSocket = new DatagramSocket();//port # is assigned by OS to the client
InetAddress IPAddress =
InetAddress.getByName("localhost");
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
byte[] sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, 7777); //data with server's IP and server's port #
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
clientSocket.setSoTimeout(1000);
clientSocket.receive(receivePacket);
// we still need to catch the exception and retry
String modifiedSentence =
new String(receivePacket.getData(),
0,
receivePacket.getLength());
System.out.println("FROM SERVER:" +
modifiedSentence);
clientSocket.close();
}
}
UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new
DatagramSocket(7777); //server will run on port #9876
byte[] receiveData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(
receivePacket.getData(),
0,
receivePacket.getLength());
InetAddress IPAddress =
receivePacket.getAddress(); //get client's IP
int port = receivePacket.getPort(); //get client's port #
System.out.println("client's port # =" + port);
System.out.println("client'sIP =" +IPAddress);
System.out.println("client's message =" +sentence);
String capitalizedSentence =
sentence.toUpperCase();
byte[] sendData = capitalizedSentence.
getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData,
sendData.length,
IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
最终我想做的是将文件路径发送到服务器,让服务器返回文件,然后将其保存到预定位置,如 C:\Desktop\Folder。
我真的不知道如何超越我现在的位置,所以你可以分享的任何建议、指示或资源都会很棒。我对此很陌生,感觉超出了我的深度。
谢谢!