java中通过socket从服务器请求特定文件
我发现了一些在客户端和服务器之间传输文件的代码。但文件位置和端口号是硬编码的。我想知道是否有一种方法可以让客户端指定他/她需要从服务器获得什么文件 - 这样当服务器收到请求时,它可以将该特定文件发送给客户端。谢谢。
编辑[1]:代码片段和上下文描述:
我根据反馈和评论添加迄今为止的代码。希望这能回答评论部分的一些问题。
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Original coder adapted from:
* http://www.rgagnon.com/javadetails/java-0542.html
*
* Best intentions:
* This program runs both as server and client.
*
* The client asks for a specific file from _
* the server x number of times in a loop.
*
* Server simply serves the file requested.
*/
public class FileServer extends Thread {
public static void server() throws IOException {
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
//Retrieve filename to serve
InputStream is = sock.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(is));
String fileName = bfr.readLine();
bfr.close();
System.out.println("Server side got the file name:" + fileName);
//Sendfile
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
public static void client(int index) throws IOException {
int filesize = 6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
//Localhost for testing
Socket sock = new Socket("127.0.0.1", 13267);
System.out.println("Connecting...");
//Ask for specific file: source1
String fileName = "source1";
OutputStream os = sock.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println(fileName);
//Receive file
byte[] mybytearray = new byte[filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source1-copy" + index);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray,
current, (mybytearray.length - current));
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end - start);
os.flush();
bos.close();
sock.close();
}
public static void main(String[] args) throws IOException {
FileServer fs = new FileServer();
fs.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(
FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < 5; i++) {
client(i);
}
}
@Override
public void run() {
try {
server();
} catch (IOException ex) {
Logger.getLogger(
FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
当我运行此代码时,它卡在“正在连接...”行。这是输出:
等待...
接受的连接:Socket[addr=/127.0.0.1,port=44939,localport=13267]
正在连接...
I found some code that transfers files between a client and a server. But the file location and port numbers are hard coded. I was wondering if there is a way in which a client can specify what file s/he needs from the server - so that when the server receives the request, it can send that particular file to the client. Thank you.
Edit [1]: Code snippet and context description:
I am adding the code I have so far, based on the feedbacks and comments. Hopefully, this answers some questions in the comment section.
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Original coder adapted from:
* http://www.rgagnon.com/javadetails/java-0542.html
*
* Best intentions:
* This program runs both as server and client.
*
* The client asks for a specific file from _
* the server x number of times in a loop.
*
* Server simply serves the file requested.
*/
public class FileServer extends Thread {
public static void server() throws IOException {
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
//Retrieve filename to serve
InputStream is = sock.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(is));
String fileName = bfr.readLine();
bfr.close();
System.out.println("Server side got the file name:" + fileName);
//Sendfile
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
public static void client(int index) throws IOException {
int filesize = 6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
//Localhost for testing
Socket sock = new Socket("127.0.0.1", 13267);
System.out.println("Connecting...");
//Ask for specific file: source1
String fileName = "source1";
OutputStream os = sock.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println(fileName);
//Receive file
byte[] mybytearray = new byte[filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source1-copy" + index);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray,
current, (mybytearray.length - current));
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end - start);
os.flush();
bos.close();
sock.close();
}
public static void main(String[] args) throws IOException {
FileServer fs = new FileServer();
fs.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(
FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < 5; i++) {
client(i);
}
}
@Override
public void run() {
try {
server();
} catch (IOException ex) {
Logger.getLogger(
FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When I run this code, it is getting stuck at "Connecting ..." line. Here is the output:
Waiting...
Accepted connection : Socket[addr=/127.0.0.1,port=44939,localport=13267]
Connecting...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@moejoe 我认为你想得太多了。
如果您已经准备好发送文件,那么要做的第一件事就是抽象出该功能,以便您可以将其作为方法运行并提供路径名/文件名。
然后,您可以使用套接字(有两种方式)将消息从客户端发送到服务器,询问您想要什么文件。除此之外,问题是如何从 UI 获取所需的文件。您可能需要让服务器提供“列出可用文件”的方法,即 ls 功能。
这一切实施起来相当简单。
@moejoe I think you're over thinking this.
If you have it in place to send a file already, then the first thing to do is abstract that functionality out so you can run it as a method and supply a pathname/filename.
Then you can use the socket (which is two way) to send a message from the client to the server asking for what file you want. Beyond that, it's a matter of how to get the file you want from the UI. You may need to have the server supply a method of "list available files", i.e. ls functionality.
This is all fairly trivial to implement.