我有一个任务来创建客户端服务器文件传输应用程序。 这可能是一个简单的例子。我尝试了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
}
}
}
}
}
我不能运行这些源文件,我不知道为什么。
你有什么具体的问题?这里有什么问题? – 2011-01-23 18:40:32
请详细说明“我无法运行这些源文件”。你究竟做了什么?究竟发生了什么? – BalusC 2011-01-23 19:01:33