socket服务端上传文件|linux下socket文件传输问题

1. 基于mfc的socket编程怎么进行文件传输

1. 采用了多线程的方法,文件传输时使用ad()开启新线程 void CClientsockDlg::OnBnClickedSend(){ pThreadSend = AfxBeginThread(Thread_Send,this);/ } 文件的发送和接收都开起了新线程 UINTThread_Send(LPVOID lpParam){ 代码略…} 2. 支持从配置文件configuration.ini中获取服务器参数 采用GetPrivateProfileString()和GetPrivateProfileInt()分别获取位于ServerConfiguration.ini文件中的String类型的IP和int类型的portCString IP;int port;GetPrivateProfileString(L"ServerConfiguration",L"IP",L"没有读取到数据!",IP.GetBuffer(10),10,L".\\configuration.ini");port=GetPrivateProfileInt(L"ServerConfiguration",L"port",0,L".\\configuration.ini");3. 采用了面向对象的设计方式,功能之间按模块划分MFC本身具有良好的面向对象的特性,本程序严格按照MFC框架结构编写代码,每个按钮对应一个功能函数,降低了代码之间的耦合性,有利于程序的扩展和复用。 void CServersockDlg::OnBnClickedChoose()void CServersockDlg::OnBnClickedSend()void CServersockDlg::OnBnClickedRecvdata()void CServersockDlg::OnBnClickedAbout()void CServersockDlg::OnBnClickedWriteini()4. 采用了CSocket类,代码相对更简单CSocket类是MFC框架对socket编程中的winsockAPI的封装,因此通过这个类管理收发数据更加便利。代码也跟那个既简单易懂。 //创建 if(!Clientsock.Socket()) { CString str; str.Format(_T("Socket创建失败:%d"),GetLastError()); AfxMessageBox(str); } //连接 if(!Clientsock.Connect(IP,port)) { CString str; str.Format(_T("Socket连接失败:%d"),GetLastError()); AfxMessageBox(str); } else { AfxMessageBox(_T("Socket连接成功")); 代码略… //发送 while(nSize<FindFileData.nFileSizeLow) { szBuff = new char[1024]; memset(szBuff,0x00,1024); nSend =file.Read(szBuff,1024); Clientsock.Send(szBuff,nSend);//发送数据 nSize += nSend; } file.Close(); delete szBuff; Clientsock.Close(); (dlg->GetDlgItem(IDC_SEND))->EnableWindow(TRUE); AfxMessageBox(_T("文件发送成功")); dlg->SetDlgItemTextW(IDC_FILEPATHNAME,_T("")); } return 0;5. 支持数据在服务器与客户端之间双向传输 本程序不但可以从客户端往服务器端传文件,而且可以从服务器端往客户端传文件。但是互传文件的方式并不是完全相同的。服务器端不管是接收文件还是发送文件始终是对绑定的端口进行监听。 //绑定 if(!Serversock.Bind(port)) { CString str; str.Format(_T("Socket绑定失败: %d"),GetLastError()); AfxMessageBox(str); } //监听 if(!Serversock.Listen(10)) { CString str; str.Format(_T("Socket监听失败:%d"),GetLastError()); AfxMessageBox(str); }客户端不管是接收文件还是发送文件始终是进行连接。 if(!Clientsock.Connect(IP,port)) { CString str; str.Format(_T("Socket连接失ì败:%d"),GetLastError()); AfxMessageBox(str); } else { 略… 6. 完全图形化操作界面二.软件使用说明 客户端主界面如图所示: 单击“选择文件”弹出文件对话框,选择一个要发送的文件,同时保存文件的路径。单击“发送”则会读取ServerConfiguration.ini文件中的配置信息(IP和port),并根据此信息建立Socket连接,发送文件。注意:服务器端应该先单击了“接受客户端数据”,否则发送失败。单击“接收”也会读取ServerConfiguration.ini文件中的配置信息(IP和port),并根据此信息建立Socket连接,接收文件。注意:服务器端应该先选择了向客户端发送的文件,并单击了“发送”,否则接受失败。单击“读取配置文件”,会从ServerConfiguration.ini文件中读取配置信息,并以可编辑的文本形式显示出来,修改完后,单击“写入配置文件”,会将修改后的信息保存到配置文件中。单击“关于”可以了解到软件相关信息。代码注释里有更详细的说明服务器端主界面如图所示 u 单击“接受客户端数据”,开始监听客户端的链接。u 单击“选择文件”弹出文件对话框,选择一个要发送的文件,同时保存文件的路径。u 单击“发送”则会读取ServerConfiguration.ini文件中的配置信息(port),并监听对应端口,准备发送文件。注意:客户端选择“接收”以后才能发送成功。u 单击“读取配置文件”,会从ServerConfiguration.ini文件中读取配置信息,并以可编辑的文本形式显示出来,修改完后,单击“写入配置文件”,会将修改后的信息保存到配置文件中。但是服务器的IP是不可以修改的,它是在程序开始运行时从服务器所在机器的网卡上获取的。u 单击“关于”可以了解到软件相关信息。u 代码注释里有更详细的说明代码下载地址:http://download.csdn.net/detail/leixiaohua1020/6320417 在此附上客户端使用CSocket发起连接的代码[cpp] view plain //—————————-发送文件的线程—————————— UINT Thread_Send(LPVOID lpParam) { CClientsockDlg *dlg=(CClientsockDlg *)lpParam; (dlg->GetDlgItem(IDC_SEND))->EnableWindow(FALSE); CSocket Clientsock; //definition socket. if(!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); } CString IP; int port; GetPrivateProfileString(L"ServerConfiguration",L"IP",L"没有读取到数据!",IP.GetBuffer(100),100,L".\\configuration.ini"); port=GetPrivateProfileInt(L"ServerConfiguration",L"port",0,L".\\configuration.ini"); //创建 if(!Clientsock.Socket()) { CString str; str.Format(_T("Socket创建失败: %d"),GetLastError()); AfxMessageBox(str); } //连接 // if(!Clientsock.Connect(_T("127.0.0.1"),8088)) if(!Clientsock.Connect(IP,port)) { CString str; str.Format(_T("Socket连接失败: %d"),GetLastError()); AfxMessageBox(str); } else { AfxMessageBox(_T("Socket连接成功")); WIN32_FIND_DATA FindFileData; CString strPathName; //定义用来保存发送文件路径的CString对象 dlg->GetDlgItemTextW(IDC_FILEPATHNAME,strPathName); FindClose(FindFirstFile(strPathName,&FindFileData)); Clientsock.Send(&FindFileData,sizeof(WIN32_FIND_DATA)); CFile file; if(!file.Open(strPathName,CFile::modeRead|CFile::typeBinary)) { AfxMessageBox(_T("文件不存在")); return 1; } UINT nSize = 0; UINT nSend = 0; char *szBuff=NULL; //发送 while(nSize<FindFileData.nFileSizeLow) { szBuff = new char[1024]; memset(szBuff,0x00,1024); nSend = file.Read(szBuff,1024); Clientsock.Send(szBuff,nSend);//发送数据 nSize += nSend; } file.Close(); delete szBuff; Clientsock.Close(); (dlg->GetDlgItem(IDC_SEND))->EnableWindow(TRUE); AfxMessageBox(_T("文件发送成功")); dlg->SetDlgItemTextW(IDC_FILEPATHNAME,_T("")); } return 0; } 以及服务器端使用CSocket监听的代码:[cpp] view plain //—————————-监听文件的线程—————————— UINT Thread_Func(LPVOID lpParam) //接收文件的线程函数 { CServersockDlg *dlg = (CServersockDlg *)lpParam; //获取对话框指针 (dlg->GetDlgItem(IDC_RECVDATA))->EnableWindow(FALSE); if(!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); } CString IP; int port; GetPrivateProfileString(L"ServerConfiguration",L"IP",L"没有读取到数据!",IP.GetBuffer(100),100,L".\\configuration.ini"); port=GetPrivateProfileInt(L"ServerConfiguration",L"port",0,L".\\configuration.ini"); char errBuf[100]={0};// 临时缓存 SYSTEMTIME t; //系统时间结构 CFile logErrorfile; if(!logErrorfile.Open(_T("logErrorfile.txt"),CFile::modeCreate|CFile::modeReadWrite)) { return 1; } CSocket Serversock; CSocket Clientsock; //创建 if(!Serversock.Socket()) { CString str; str.Format(_T("Socket创建失败: %d"),GetLastError()); AfxMessageBox(str); } BOOL bOptVal = TRUE; int bOptLen = sizeof(BOOL); Serversock.SetSockOpt(SO_REUSEADDR,(void *)&bOptVal,bOptLen,SOL_SOCKET); //绑定 if(!Serversock.Bind(port)) { CString str; str.Format(_T("Socket绑定失败: %d"),GetLastError()); AfxMessageBox(str); } //监听 if(!Serversock.Listen(10)) { CString str; str.Format(_T("Socket监听失败: %d"),GetLastError()); AfxMessageBox(str); } GetLocalTime(&t); sprintf_s(errBuf,"服务器已经启动…正在等待接收文件…\r\n时间:%d年%d月%d日 %2d:%2d:%2d \r\n",t.wYear,t.wMonth,t.wDay, t.wHour,t.wMinute,t.wSecond); int len = strlen(errBuf); logErrorfile.Write(errBuf,len); AfxMessageBox(_T("启动成功等待接收文件")); while(1) { //AfxMessageBox(_T("服务器启动成功…")); if(!Serversock.Accept(Clientsock)) //等待接收 { continue; } else { WIN32_FIND_DATA FileInfo; Clientsock.Receive(&FileInfo,sizeof(WIN32_FIND_DATA)); CFile file; file.Open(FileInfo.cFileName,CFile::modeCreate|CFile::modeWrite); //AfxMessageBox(FileInfo.cFileName); int length = sizeof(FileInfo.cFileName); logErrorfile.Write(FileInfo.cFileName,length); //Receive文件的数据 UINT nSize = 0; UINT nData = 0; char *szBuff=NULL; while(nSize<FileInfo.nFileSizeLow) { szBuff = new char[1024]; memset(szBuff,0x00,1024); nData=Clientsock.Receive(szBuff,1024); file.Write(szBuff,nData); nSize+=nData; } delete szBuff; Serversock.Close(); Clientsock.Close(); file.Close(); (dlg->GetDlgItem(IDC_RECVDATA))->EnableWindow(TRUE); sprintf_s(errBuf,"文件接收成功…\r\n时间:%d年%d月%d日 %2d:%2d:%2d \r\n",t.wYear,t.wMonth,t.wDay, t.wHour,t.wMinute,t.wSecond); int len = strlen(errBuf); logErrorfile.Write(errBuf,len); //AfxMessageBox(_T("文件接收成功…")); break; } } return 0; }

2. c# c/s结构Socket上传文件的代码

发送端(client)

private void button2_Click(object sender, EventArgs e) { this.button2.Enabled = false; Thread TempThread = new Thread(new ThreadStart(this.StartSend)); TempThread.Start(); }

private void StartSend() { //FileInfo EzoneFile = new FileInfo(this.textBox1.Text);

string path = @"E:old F directoryTangWeikanggeew1.jpg";

FileInfo EzoneFile = new FileInfo(path);

FileStream EzoneStream = EzoneFile.OpenRead();

int PacketSize = 100000;

int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));

// this.textBox8.Text = PacketCount.ToString();

// this.progressBar1.Maximum = PacketCount;

int LastDataPacket = (int)(EzoneStream.Length – ((long)(PacketSize * PacketCount)));

// this.textBox9.Text = LastDataPacket.ToString(); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

client.Connect(ipep);

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));

// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));

byte[] data = new byte[PacketSize];

for(int i=0; i<PacketCount; i++) { EzoneStream.Read(data, 0, data.Length);

TransferFiles.SendVarData(client, data);

// this.textBox10.Text = ((int)(i + 1)).ToString();

// this.progressBar1.PerformStep(); }

if(LastDataPacket != 0) { data = new byte[LastDataPacket];

EzoneStream.Read(data, 0, data.Length);

TransferFiles.SendVarData(client,data);

// this.progressBar1.Value = this.progressBar1.Maximum; } client.Close();

EzoneStream.Close();

this.button2.Enabled = true; }

接收端(server)

private void button2_Click(object sender, EventArgs e) { //int i = 0; //FileStream recfs = new FileStream("E:\kangge.jpg", FileMode.OpenOrCreate); //Byte[] recbyte = new Byte[2000000]; //Socket hostsocket = receive.Accept(); //BinaryWriter newfilestr = new BinaryWriter(recfs); //hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None); //for (i = 0; i < recbyte.Length; i++) //{ // newfilestr.Write(recbyte, i, 1); //} //recfs.Close();

//hostsocket.Shutdown(SocketShutdown.Receive); //hostsocket.Close();

this.button2.Enabled = false; Thread TempThread = new Thread(new ThreadStart(this.StartReceive)); TempThread.Start(); } private void StartReceive() { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);

Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

server.Bind(ipep);

server.Listen(10);

Socket client = server.Accept();

// IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;

// string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

// string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));

// int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));

// string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)); int file_name = 1;

string fileaddr = "E:\old F directory\TangWei\Copy of kangge\" + file_name.ToString() + ".jpg"; FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);

// int SendedCount = 0;

while(true) { byte[] data = TransferFiles.ReceiveVarData(client); if(data.Length == 0) { break; } else { // SendedCount++; MyFileStream.Write(data, 0, data.Length); } }

MyFileStream.Close();

client.Close();

this.button2.Enabled = true; }

公共类。 TransferFiles

class TransferFiles {

public TransferFiles() {

}

public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent. { int total = 0; int size = data.Length; int dataleft = size; int sent; byte[] datasize = new byte[4]; datasize = BitConverter.GetBytes(size); sent = s.Send(datasize);//send the size of data array.

while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; }

return total; }

public static byte[] ReceiveVarData(Socket s) // return array that store the received data. { int total = 0; int recv; byte[] datasize = new byte[4]; recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array. int size = BitConverter.ToInt32(datasize, 0); int dataleft = size; byte[] data = new byte[size];

while (total < size) { recv = s.Receive(data, total, dataleft, SocketFlags.None); if (recv == 0) { data = null; break; } total += recv; dataleft -= recv; }

return data;

} }

3. 用java socket实现一个服务器对多个客户端的文件传输

通过socket可以用如下方式进行。1.启动服务端代码。2.启动客户端自动连接服务端。3.服务端上传文件,保存文件和路径。4.将路径发送给连接服务端的客户端。

4. 怎么用java的socket进行文件传输谁能给个简单的例子,包括发送端和接收端。

java中的网络信息传输方式是基于TCP协议或者UD协议P的,socket是基于TCP协议的例子1(1)客户端程序:import java.io.*;import java.net.*;public class Client{ public static void main(String args[]) { String s=null; Socket mysocket; DataInputStream in=null; DataOutputStream out=null; try{ mysocket=new Socket("localhost",4331); in=new DataInputStream(mysocket.getInputStream()); out=new DataOutputStream(mysocket.getOutputStream()); out.writeUTF("你好!");//通过 out向"线路"写入信息。 while(true) { s=in.readUTF();//通过使用in读取服务器放入"线路"里的信息。堵塞状态, //除非读取到信息。 out.writeUTF(":"+Math.random()); System.out.println("客户收到:"+s); Thread.sleep(500); } } catch(IOException e) { System.out.println("无法连接"); } catch(InterruptedException e){} } }(2)服务器端程序:import java.io.*;import java.net.*;public class Server{ public static void main(String args[]) { ServerSocket server=null; Socket you=null;String s=null; DataOutputStream out=null;DataInputStream in=null; try{ server=new ServerSocket(4331);} catch(IOException e1){System.out.println("ERRO:"+e1);} try{ you=server.accept(); in=new DataInputStream(you.getInputStream()); out=new DataOutputStream(you.getOutputStream()); while(true) { s=in.readUTF();// 通过使用in读取客户放入"线路"里的信息。堵塞状态, //除非读取到信息。 out.writeUTF("你好:我是服务器");//通过 out向"线路"写入信息. out.writeUTF("你说的数是:"+s); System.out.println("服务器收到:"+s); Thread.sleep(500); } } catch(IOException e) { System.out.println(""+e); } catch(InterruptedException e){} }}例子(2)(1) 客户端import java.net.*;import java.io.*;import java.awt.*;import java.awt.event.*;import java.applet.*;public class Computer_client extends Applet implements Runnable,ActionListener{ Button 计算;TextField 输入三边长度文本框,计算结果文本框; Socket socket=null; DataInputStream in=null; DataOutputStream out=null; Thread thread; public void init() { setLayout(new GridLayout(2,2)); Panel p1=new Panel(),p2=new Panel(); 计算=new Button(" 计算"); 输入三边长度文本框=new TextField(12);计算结果文本框=new TextField(12); p1.add(new Label("输入三角形三边的长度,用逗号或空格分隔:")); p1.add( 输入三边长度文本框); p2.add(new Label("计算结果:"));p2.add(计算结果文本框);p2.add(计算); 计算.addActionListener(this); add(p1);add(p2); } public void start() { try { //和小程序所驻留的服务器建立套接字连接: socket = new Socket(this.getCodeBase().getHost(), 4331); in =new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); } catch (IOException e){} if(thread == null) { thread = new Thread(this); thread.start(); } } public void run() { String s=null; while(true) { try{ s=in.readUTF();//堵塞状态,除非读取到信息。 计算结果文本框.setText(s); } catch(IOException e) { 计算结果文本框.setText("与服务器已断开"); break;} } } public void actionPerformed(ActionEvent e) { if(e.getSource()==计算) { String s=输入三边长度文本框.getText(); if(s!=null) { try { out.writeUTF(s); } catch(IOException e1){} } } }} (2) 服务器端import java.io.*;import java.net.*;import java.util.*;import java.sql.*;public class Computer_server { public static void main(String args[]) { ServerSocket server=null;Server_thread thread; Socket you=null; while(true) { try{ server=new ServerSocket(4331); } catch(IOException e1) { System.out.println("正在监听"); //ServerSocket对象不能重复创建。 } try{ you=server.accept(); System.out.println("客户的地址:"+you.getInetAddress()); } catch (IOException e) { System.out.println("正在等待客户"); } if(you!=null) { new Server_thread(you).start(); //为每个客户启动一个专门的线程。 } else { continue; } } }}class Server_thread extends Thread{ Socket socket;Connection Con=null;Statement Stmt=null; DataOutputStream out=null;DataInputStream in=null;int n=0; String s=null; Server_thread(Socket t) { socket=t; try { in=new DataInputStream(socket.getInputStream()); out=new DataOutputStream(socket.getOutputStream()); } catch (IOException e) {} } public void run() { while(true) { double a[]=new double[3] ;int i=0; try{ s=in.readUTF();堵塞状态,除非读取到信息。 StringTokenizer fenxi=new StringTokenizer(s," ,"); while(fenxi.hasMoreTokens()) { String temp=fenxi.nextToken(); try{ a[i]=Double.valueOf(temp).doubleValue();i++; } catch(NumberFormatException e) { out.writeUTF("请输入数字字符"); } } double p=(a[0]+a[1]+a[2])/2.0; out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2]))); sleep(2); } catch(InterruptedException e){} catch (IOException e) { System.out.println("客户离开"); break; } } } }这些例子都是Java2实用教程上的.

5. linux下socket文件传输问题

如果你的客户端在发送文件时,每次都重新connect,再进行数据传输,则你的程序无回法解决数据的区分。答如果客户端是一次connect循环发送,后台服务循环接收,则(1)如果你的服务端只有一个进程(不支持并发),则A和B不会同时运行,只能按顺序接收完A再接收B(2)如果,每一个新链接上来,你都建立一个新的进程去工作,则不会有问题。

6. java socket传送文件

客户端代码如下:

importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.net.InetSocketAddress;importjava.net.Socket;/***文件发送客户端主程序*@authoradmin_Hzw**/publicclassBxClient{/***程序main方法*@paramargs*@throwsIOException*/publicstaticvoidmain(String[]args)throwsIOException{intlength=0;doublesumL=0;byte[]sendBytes=null;Socketsocket=null;DataOutputStreamdos=null;FileInputStreamfis=null;booleanbool=false;try{Filefile=newFile("D:/天啊.zip");//要传输的文件路径longl=file.length();socket=newSocket();socket.connect(newInetSocketAddress("127.0.0.1",48123));dos=newDataOutputStream(socket.getOutputStream());fis=newFileInputStream(file);sendBytes=newbyte[1024];while((length=fis.read(sendBytes,0,sendBytes.length))>0){sumL+=length;System.out.println("已传输:"+((sumL/l)*100)+"%");dos.write(sendBytes,0,length);dos.flush();}//虽然数据类型不同,但JAVA会自动转换成相同数据类型后在做比较if(sumL==l){bool=true;}}catch(Exceptione){System.out.println("客户端文件传输异常");bool=false;e.printStackTrace();}finally{if(dos!=null)dos.close();if(fis!=null)fis.close();if(socket!=null)socket.close();}System.out.println(bool?"成功":"失败");}}

服务端代码如下:

importjava.io.DataInputStream;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Random;importcom.boxun.util.GetDate;/***接收文件服务*@authoradmin_Hzw**/publicclassBxServerSocket{/***工程main方法*@paramargs*/publicstaticvoidmain(String[]args){try{finalServerSocketserver=newServerSocket(48123);Threadth=newThread(newRunnable(){publicvoidrun(){while(true){try{System.out.println("开始监听…");/**如果没有访问它会自动等待*/Socketsocket=server.accept();System.out.println("有链接");receiveFile(socket);}catch(Exceptione){System.out.println("服务器异常");e.printStackTrace();}}}});th.run();//启动线程运行}catch(Exceptione){e.printStackTrace();}}publicvoidrun(){}/***接收文件方法*@paramsocket*@throwsIOException*/publicstaticvoidreceiveFile(Socketsocket)throwsIOException{byte[]inputByte=null;intlength=0;DataInputStreamdis=null;FileOutputStreamfos=null;StringfilePath="D:/temp/"+GetDate.getDate()+"SJ"+newRandom().nextInt(10000)+".zip";try{try{dis=newDataInputStream(socket.getInputStream());Filef=newFile("D:/temp");if(!f.exists()){f.mkdir();}/**文件存储位置*/fos=newFileOutputStream(newFile(filePath));inputByte=newbyte[1024];System.out.println("开始接收数据…");while((length=dis.read(inputByte,0,inputByte.length))>0){fos.write(inputByte,0,length);fos.flush();}System.out.println("完成接收:"+filePath);}finally{if(fos!=null)fos.close();if(dis!=null)dis.close();if(socket!=null)socket.close();}}catch(Exceptione){e.printStackTrace();}}}

7. 关于用JAVA的SOCKET传输文件

点对点传输文件/*import java.io.*;import java.net.*;import java.util.*;*/private HttpURLConnection connection;//存储连接 private int downsize = -1;//下载文件大小,初始值为-1 private int downed = 0;//文加已下载大小,初始值为0 private RandomAccessFile savefile;//记录下载信息存储文件 private URL fileurl;//记录要下载文件的地址 private DataInputStream fileStream;//记录下载的数据流try{ /*开始创建下载的存储文件,并初始化值*/ File tempfileobject = new File("h:\\webwork-2.1.7.zip"); if(!tempfileobject.exists()){ /*文件不存在则建立*/ tempfileobject.createNewFile(); } savefile = new RandomAccessFile(tempfileobject,"rw"); /*建立连接*/ fileurl = new URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip"); connection = (HttpURLConnection)fileurl.openConnection(); connection.setRequestProperty("Range","byte="+this.downed+"-"); this.downsize = connection.getContentLength(); //System.out.println(connection.getContentLength()); new Thread(this).start(); } catch(Exception e){ System.out.println(e.toString()); System.out.println("构建器错误"); System.exit(0); } public void run(){ /*开始下载文件,以下测试非断点续传,下载的文件存在问题*/ try{ System.out.println("begin!"); Date begintime = new Date(); begintime.setTime(new Date().getTime()); byte[] filebyte; int onecelen; //System.out.println(this.connection.getInputStream().getClass().getName()); this.fileStream = new DataInputStream( new BufferedInputStream( this.connection.getInputStream())); System.out.println("size = " + this.downsize); while(this.downsize != this.downed){ if(this.downsize – this.downed > 262144){//设置为最大256KB的缓存 filebyte = new byte[262144]; onecelen = 262144; } else{ filebyte = new byte[this.downsize – this.downed]; onecelen = this.downsize – this.downed; } onecelen = this.fileStream.read(filebyte,0,onecelen); this.savefile.write(filebyte,0,onecelen); this.downed += onecelen; System.out.println(this.downed); } this.savefile.close(); System.out.println("end!"); System.out.println(begintime.getTime()); System.out.println(new Date().getTime()); System.out.println(begintime.getTime() – new Date().getTime()); } catch(Exception e){ System.out.println(e.toString()); System.out.println("run()方法有问题!"); }}/***//FileClient.javaimport java.io.*;import java.net.*;public class FileClient {public static void main(String[] args) throws Exception {//使用本地文件系统接受网络数据并存为新文件File file = new File("d:\\fmd.doc");file.createNewFile();RandomAccessFile raf = new RandomAccessFile(file, "rw");// 通过Socket连接文件服务器Socket server = new Socket(InetAddress.getLocalHost(), 3318);//创建网络接受流接受服务器文件数据InputStream netIn = server.getInputStream();InputStream in = new DataInputStream(new BufferedInputStream(netIn));//创建缓冲区缓冲网络数据byte[] buf = new byte[2048];int num = in.read(buf);while (num != (-1)) {//是否读完所有数据raf.write(buf, 0, num);//将数据写往文件raf.skipBytes(num);//顺序写文件字节num = in.read(buf);//继续从网络中读取文件}in.close();raf.close();}}//FileServer.javaimport java.io.*;import java.util.*;import java.net.*;public class FileServer {public static void main(String[] args) throws Exception {//创建文件流用来读取文件中的数据File file = new File("d:\\系统特点.doc");FileInputStream fos = new FileInputStream(file);//创建网络服务器接受客户请求ServerSocket ss = new ServerSocket(8801);Socket client = ss.accept();//创建网络输出流并提供数据包装器OutputStream netOut = client.getOutputStream();OutputStream doc = new DataOutputStream(new BufferedOutputStream(netOut));//创建文件读取缓冲区byte[] buf = new byte[2048];int num = fos.read(buf);while (num != (-1)) {//是否读完文件doc.write(buf, 0, num);//把文件数据写出网络缓冲区doc.flush();//刷新缓冲区把数据写往客户端num = fos.read(buf);//继续从文件中读取数据}fos.close();doc.close();}}*/


赞 (0)