关于socket传输文件 我要写一个基于socket点对点的文件传输的功能,谁可以讲下,如何再传输的过程中获取文件传输的百分比,还有文件的传输速率,谁有做过的,发点代码让我看下,不甚感激!! 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 先定义好你的文件传输协议,可以参照 HTTP 协议,在发送文件实际正文内容前先发送文件的相关属性信息,比如文件大小,文件修改时间,文件MD5码(用于让接收方校验文件)等等,后面就好办了,用实际接收到字节数与文件总大小一除就能得到实时的接收百分比。传输率用接收到的字节总数和所耗时间相除能得到平均的传输速率。基本思路是这样,更完善的协议设计可以参考一下 FTP 等成熟的文件传输协议。 恩,先把文件大小传过去。比如定义前4个字节是为文件大小保留的,然后根据inputstream.read(byte[])来统计获得部分的大小,经过时间,然后自己算。 package server;import java.io.BufferedInputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.net.ServerSocket;import java.net.Socket;import javax.swing.JOptionPane;public class Server { int port = 8821; void start() { Socket s = null; try { ServerSocket ss = new ServerSocket(port); while (true) { // String filePath = JOptionPane.showInputDialog("Enter file name (include file path & extentionname)"); File fi = new File(filePath); System.out.println("FileLength:" + (int) fi.length()); // public Socket accept() throws // s = ss.accept(); System.out.println("Establish socket connection!"); DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream())); dis.readByte(); DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath))); DataOutputStream ps = new DataOutputStream(s.getOutputStream()); // ps.writeUTF(fi.getName()); ps.flush(); ps.writeLong((long) fi.length()); ps.flush(); int bufferSize = 8192; byte[] buf = new byte[bufferSize]; while (true) { int read = 0; if (fis != null) { read = fis.read(buf); } if (read == -1) { break; } ps.write(buf, 0, read); } ps.flush(); // // fis.close(); s.close(); System.out.println("File has been transfered!"); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String arg[]) { new Server().start(); }} 客户端程序package client;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileOutputStream;import javax.swing.JOptionPane;public class Client { private ClientSocket cs = null; private String ip = JOptionPane.showInputDialog("Enter your server IP:"); private int port = 8821; private String sendMessage = "Windwos"; public Client() { try { if (createConnection()) { sendMessage(); getMessage(); } } catch (Exception ex) { ex.printStackTrace(); } } private boolean createConnection() { cs = new ClientSocket(ip, port); try { cs.CreateConnection(); System.out.print("Link to server["+ip+"] successfully!" + "\n"); return true; } catch (Exception e) { System.out.print("Link to server["+ip+"] fail!" + "\n"); return false; } } private void sendMessage() { if (cs == null) return; try { cs.sendMessage(sendMessage); } catch (Exception e) { System.out.print("Fail to send message!" + "\n"); } } private void getMessage() { if (cs == null) return; DataInputStream inputStream = null; try { inputStream = cs.getMessageStream(); } catch (Exception e) { System.out.print("Reciver message buffer error!\n"); return; } try { // String savePath = JOptionPane.showInputDialog("File save to:"); int bufferSize = 8192; byte[] buf = new byte[bufferSize]; int passedlen = 0; long len=0; savePath += inputStream.readUTF(); DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)))); len = inputStream.readLong(); System.out.println("File Length:" + len + "\n"); System.out.println("Start to receive file!" + "\n"); while (true) { int read = 0; if (inputStream != null) { read = inputStream.read(buf); } passedlen += read; if (read == -1) { break; } // System.out.println("File has been received" + (passedlen * 100/ len) + "%\n"); fileOut.write(buf, 0, read); } System.out.println("Finished to receive file,file has been saved to " + savePath + "\n"); fileOut.close(); } catch (Exception e) { System.out.println("Receive message error!" + "\n"); return; } } public static void main(String arg[]) { new Client(); }}package client;import java.net.*;import java.io.*;public class ClientSocket { private String ip; private int port; private Socket socket = null; DataOutputStream out = null; DataInputStream getMessageStream = null; public ClientSocket(String ip, int port) { this.ip = ip; this.port = port; } /** *//** * Build socket connection * * @throws Exception * exception */ public void CreateConnection() throws Exception { try { socket = new Socket(ip, port); } catch (Exception e) { e.printStackTrace(); if (socket != null) socket.close(); throw e; } finally { } } public void sendMessage(String sendMessage) throws Exception { try { out = new DataOutputStream(socket.getOutputStream()); if (sendMessage.equals("Windows")) { out.writeByte(0x1); out.flush(); return; } if (sendMessage.equals("Unix")) { out.writeByte(0x2); out.flush(); return; } if (sendMessage.equals("Linux")) { out.writeByte(0x3); out.flush(); } else { out.writeUTF(sendMessage); out.flush(); } } catch (Exception e) { e.printStackTrace(); if (out != null) out.close(); throw e; } finally { } } public DataInputStream getMessageStream() throws Exception { try { getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream())); return getMessageStream; } catch (Exception e) { e.printStackTrace(); if (getMessageStream != null) getMessageStream.close(); throw e; } finally { } } public void shutDownConnection() { try { if (out != null) out.close(); if (getMessageStream != null) getMessageStream.close(); if (socket != null) socket.close(); } catch (Exception e) { } }} 这个可以用,而且支持超大(大于1G)文件传输,支持不同平台在Ubuntu8.04 和winxp下测试通过。最好把他们分别打包成服务器端和客户端jar文件以后使用时方便点代码是我从网上下的,然后把说明改成英文的,以避免显示中文乱码,其实还是有一点可以把代码改成支持国际化的,那样在任何平台都可以显示中文了,其实就是把中文全部换成中文的16进制unicode代码就OK了。懒得改了,加了可视化文件路径,文件名输入对话框有显示文件传送进度,但是是命令行式的。似乎显示的进度不正确,有待修正最近很忙,有时间再加个界面,显示上传进度条,文件选择器之类的。还有把我写的点对点聊天程序也整合一下进去。好久没写java程序了,都生疏了。 如何在数据库赋予权限 byte b=2;b=b+1;可以通过b=b-1不行,这是为什么? 怎么获得数据库表名列表? 这是什么意思? 一个thinking java中关于关键字this的问题 面试题 请高手指教 怎样解决JBuilder8里面光标不能正确定位的问题? 写的记事本程序为什么图片有的显示出来有的显示不出来? 初学JAVA。难以理解引用传递和值传递他们的关系。高手可以进来给小弟说说么? 怎样把Word 文件转化为.Hlp文件 (在线等候)谢谢 急问FRAME程序如何发布? jpasswordfield 的问题
package server;import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;public class Server {
int port = 8821; void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
//
String filePath = JOptionPane.showInputDialog("Enter file name (include file path & extentionname)");
File fi = new File(filePath); System.out.println("FileLength:" + (int) fi.length()); // public Socket accept() throws
// s = ss.accept();
System.out.println("Establish socket connection!");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte(); DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush(); int bufferSize = 8192;
byte[] buf = new byte[bufferSize]; while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
} if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
//
//
fis.close();
s.close();
System.out.println("File has been transfered!");
} } catch (Exception e) {
e.printStackTrace();
}
} public static void main(String arg[]) {
new Server().start();
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import javax.swing.JOptionPane;public class Client {
private ClientSocket cs = null; private String ip = JOptionPane.showInputDialog("Enter your server IP:"); private int port = 8821; private String sendMessage = "Windwos"; public Client() {
try {
if (createConnection()) {
sendMessage();
getMessage();
} } catch (Exception ex) {
ex.printStackTrace();
}
} private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("Link to server["+ip+"] successfully!" + "\n");
return true;
} catch (Exception e) {
System.out.print("Link to server["+ip+"] fail!" + "\n");
return false;
} } private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("Fail to send message!" + "\n");
}
} private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("Reciver message buffer error!\n");
return;
} try {
//
String savePath = JOptionPane.showInputDialog("File save to:");
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;
savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();
System.out.println("File Length:" + len + "\n");
System.out.println("Start to receive file!" + "\n");
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//
System.out.println("File has been received" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("Finished to receive file,file has been saved to " + savePath + "\n"); fileOut.close();
} catch (Exception e) {
System.out.println("Receive message error!" + "\n");
return;
}
} public static void main(String arg[]) {
new Client();
}
}package client;import java.net.*;
import java.io.*;public class ClientSocket {
private String ip; private int port; private Socket socket = null; DataOutputStream out = null; DataInputStream getMessageStream = null; public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
} /** *//**
* Build socket connection
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
} public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
} public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
} public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) { }
}
}