作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我的任务是创建客户端-服务器文件传输应用程序。这可能是一个简单的例子。我尝试了SOF中类似问题中给出的示例,但他们无法传输文件。
我正在尝试通过套接字与客户端和服务器通信。如果有人可以帮助我,我会很高兴。
客户端会将文件上传到服务器。客户端也可以从服务器下载文件。这就是我创建应用程序的方式。
这是客户端代码:
package wdc;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket("127.0.0.1", 3248);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("C:\\testout.pdf");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
服务器端代码:
package wds;
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File("C:\\testserver.pdf");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
我无法运行这些源文件,我不知道为什么。
最佳答案
我看了下代码,乍一看似乎没什么问题。所以,我按原样复制它,将服务器代码中使用的文件更改为我系统上存在的文件并运行代码。它工作得很好,所以至少我可以向你保证代码是正确的并且它做了它应该做的事情。我在 Ubuntu 机器上运行了我的代码,但我不确定这会如何影响结果。
我的帮助只是一些提示:1) 你运行的是 TCPServer 文件然后是 TCPClient? (愚蠢,我知道,但你永远不知道)2) 是否有可能正在使用端口 3248 的进程?3)运行文件的进程是否有权读/写指定的路径?4) TCPServer 中指定的文件是否真实存在?5) 您是否尝试过在 IDE 之外运行类文件 - 无论哪种方式,学习如何独立于 IDE 都是很好的。
希望这对您有所帮助,祝您作业顺利。
关于java - 服务器-客户端之间的文件上传和下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4775617/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!