直接进入主题,JAVA应用socket传输文件代码。
服务器:
public class TestSocketServer {
private ServerSocket server;
private Socket socket;
public void runSocket(){
try{
server = new ServerSocket(4949);
System.out.println("waiting for client to connect on...");
socket = server.accept();
String filePath = "D://abc.zip";
DataOutputStream ps = new DataOutputStream(socket.getOutputStream());
TransferServerMethod.transferMethodForServer(filePath, ps);
socket.close();
System.out.println("文件传输完成");
}catch(SocketException e){
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}catch(IOException e){
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
TestSocketServer tss = new TestSocketServer();
tss.runSocket();
// JOptionPane.showMessageDialog(null, "收到");
}
}
服务器端传输方法:
public class TransferServerMethod {
public static void transferMethodForServer(String sourceFileDir,DataOutputStream dos){
File fi = new File(sourceFileDir);
try {
DataInputStream fis = new DataInputStream(new BufferedInputStream( new FileInputStream(fi)));
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
dos.write(buf, 0, read);
}
dos.flush();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端:
public class SocketTestClient {
public static void main(String args[]) {
Socket connection;
DataInputStream input;
String savePath = "E://receive.zip";
BufferedOutputStream bos;
DataOutputStream fileOut;
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];
FileOutputStream fos;
try {
fos = new FileOutputStream(savePath);
bos = new BufferedOutputStream(fos);
fileOut = new DataOutputStream(bos);
connection = new Socket("127.0.0.1",4949);
input = new DataInputStream(connection.getInputStream());
while (true) {
int read = 0;
if (input != null) {
read = input.read(buf);
}
if (read == -1) {
break;
} f
ileOut.write(buf, 0, read);
}
fileOut.close();
connection.close();
} catch(SecurityException e){
System.out.println("SecurityException when connecting Server!");
} catch(IOException e){
System.out.println("IOException when connecting Server!");
}
}
}
值得说明的是:当你想应用socket传输文件并且只将它作为一个子功能,也就是在传输文件后还想让服务器继续监听原有端口时,就需要用到两个socket对象,将上面的传输功能嵌套在另一个socket中,因为在传输文件时需要关闭socket来确定文件传输结束。这是要注意的,如果有其他方法不需要关闭还请指教。