利用java socket实现文件传输
1.服务器端 package sterning;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;public class ServerTest {int port = 8821;void start() {Socket s = null;try {ServerSocket ss = new ServerSocket(port);while (true) {// 选择进行传输的文件String filePath = "D:\lib.rar";File fi = new File(filePath);System.out.println("文件长度:" + (int) fi.length());// public Socket accept() throws// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。s = ss.accept();System.out.println("建立socket链接");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());//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。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();// 注意关闭socket链接哦,不然客户端会等待server的数据过来,// 直到socket超时,导致数据不完整。fis.close();s.close();System.out.println("文件传输完成");}} catch (Exception e) {e.printStackTrace();}}public static void main(String arg[]) {new ServerTest().start();}}2.socket的Util辅助类package sterning;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;}/** *//*** 创建socket连接** @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) {}}}3.客户端package sterning;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileOutputStream;public class ClientTest {private ClientSocket cs = null;private String ip = "localhost";// 设置成服务器IPprivate int port = 8821;private String sendMessage = "Windwos";public ClientTest() {try {if (createConnection()) {sendMessage();getMessage();}} catch (Exception ex) {ex.printStackTrace();}}private boolean createConnection() {cs = new ClientSocket(ip, port);try {cs.CreateConnection();System.out.print("连接服务器成功!" + "n");return true;} catch (Exception e) {System.out.print("连接服务器失败!" + "n");return false;}}private void sendMessage() {if (cs == null)return;try {cs.sendMessage(sendMessage);} catch (Exception e) {System.out.print("发送消息失败!" + "n");}}private void getMessage() {if (cs == null)return;DataInputStream inputStream = null;try {inputStream = cs.getMessageStream();} catch (Exception e) {System.out.print("接收消息缓存错误n");return;}try {//本地保存路径,文件名会自动从服务器端继承而来。String savePath = "E:\";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("文件的长度为:" + len + "n");System.out.println("开始接收文件!" + "n");while (true) {int read = 0;if (inputStream != null) {read = inputStream.read(buf);}passedlen += read;if (read == -1) {break;}//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比System.out.println("文件接收了" +(passedlen * 100/ len) + "%n");fileOut.write(buf, 0, read);}System.out.println("接收完成,文件存为" + savePath + "n");fileOut.close();} catch (Exception e) {System.out.println("接收消息错误" + "n");return;}}public static void main(String arg[]) {new ClientTest();} }
java中的网络信息传输方式基于TCP协议和UD协议P的,socket是基于TCP协议的实现代码如下: import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.net.InetSocketAddress;import java.net.Socket;public class ClientTcpSend {public static void main(String[] args) {int length = 0;byte[] sendBytes = null;Socket socket = null;DataOutputStream dos = null;FileInputStream fis = null;try {try {socket = new Socket();socket.connect(new InetSocketAddress("127.0.0.1", 33456),dos = new DataOutputStream(socket.getOutputStream());File file = new File("/root/6674541037_c3a9c8b64c_b.jpg");Ffis = new FileInputStream(file);sendBytes = new byte[1024];while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {dos.write(sendBytes, 0, length);dos.flush();}} finally {if (dos != null)dos.close();if (fis != null)fis.close();if (socket != null)socket.close();}} catch (Exception e) {e.printStackTrace();}} }
代码如下: /*import java.io.*;import java.net.*;import java.util.*;*/private HttpURLConnection connection;//存储连接private int downsize = -1;//下载文件大小,初始值为-1private int downed = 0;//文加已下载大小,初始值为0private 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();}} */

基于mfc的socket编程怎么进行文件传输
1.采用了多线程的方法,文件传输时使用AfxBeginThread()开启新线程 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(nSizeGetDlgItem(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 copy//----------------------------发送文件的线程------------------------------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(nSizeGetDlgItem(IDC_SEND))->EnableWindow(TRUE);AfxMessageBox(_T("文件发送成功"));dlg->SetDlgItemTextW(IDC_FILEPATHNAME,_T(""));}return 0;}以及服务器端使用CSocket监听的代码:[cpp] view plain copy//----------------------------监听文件的线程------------------------------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,"服务器已经启动...正在等待接收文件...rn时间:%d年%d月%d日 %2d:%2d:%2d rn",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(nSizeGetDlgItem(IDC_RECVDATA))->EnableWindow(TRUE);sprintf_s(errBuf,"文件接收成功...rn时间:%d年%d月%d日 %2d:%2d:%2d rn",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; }
首先创建一个MFC项目,修改名称以及存放路径。 项目配置,在向导过程中选择“基于对话框”模式,并选择“windows”套接字。设计服务器界面,控件有:4个静态文本(Static Text),最后一个用于指示用户连接个数;一个按钮(Button),用于打开或关闭服务器;2个编辑框(Edit Control),一个用于输入端口号,另一个只读的用于显示事件日志。修改各个控件的属性,注意编辑框2还要把Multiline和Vertical Scroll属性选为true,以实现多行显示并自带滚动条。1、 给控件添加变量和事件处理函数,这个通过类向导就可以完成,变量如上表所示,事件只有“按钮按下”一个,双击按钮自动生成函数,后面添加相关代码即可。2、 在类视图中添加一个新类CServerSocket,派生于CSocket类,对该类进行类向导添加三个函数: OnAccept()、OnClose()、OnReceive()

基于Java Socket实现文件传输
import java.io.*; import java.net.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Client1 extends JFrame{private JTextField enter,Iptext;private JTextArea display;private JLabel Iplabel;private JPanel upPanel;JButton clientMessageButton,connectButton,DisConnectButton;ObjectOutputStream output;ObjectInputStream input;Socket socket1;String message=" ";public Client1(){super("客户端");Container c=getContentPane();clientMessageButton=new JButton("发送");c.add(clientMessageButton,BorderLayout.EAST);clientMessageButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){sendData(enter.getText());
}});DisConnectButton=new JButton("断开连接");DisConnectButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){DisConnect();
}});Iptext=new JTextField(10);Iptext.setText("");Iptext.setEnabled(true);Iptext.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){connect();
}});Iplabel=new JLabel("服务器IP:");connectButton=new JButton("连接");connectButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){connect();
}});upPanel=new JPanel();upPanel.add(connectButton);upPanel.add(DisConnectButton);upPanel.add(Iplabel);upPanel.add(Iptext);enter=new JTextField();enter.setEnabled(true);enter.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){sendData(enter.getText());
}});c.add(enter,BorderLayout.SOUTH);c.add(upPanel,BorderLayout.NORTH);display=new JTextArea();c.add(new JScrollPane(display),BorderLayout.CENTER);setSize(300,450);show();}public void connect(){try{display.setText("准备连接...n");String s=Iptext.getText();socket1=new Socket(InetAddress.getByName(s),8888);display.append("连接到: "+socket1.getInetAddress().getHostName());display.append("n主机IP为:"+socket1.getInetAddress().toString());output=new ObjectOutputStream(socket1.getOutputStream());output.flush();do{try{message=(String)input.readObject();display.append("n"+message);}catch(IOException e){display.append("n无法获得信息");}catch(ClassNotFoundException e){}}while(!message.equals("end"));display.append("n关闭连接");output.close();input.close();socket1.close();}catch(EOFException eof){System.out.println(eof);}catch(IOException e){e.printStackTrace();}}public void DisConnect(){try{display.append("n关闭连接");output.close();input.close();socket1.close();}catch(Exception e){}}private void sendData(String s){try{message=s;output.writeObject("客户消息: "+s);display.append("n客户:"+s);output.flush();enter.setText(" ");}catch(Exception e){display.append("n发生错误");}}public static void main(String args[])//throws NullPointerException{Client1 app=new Client1();app.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});//app.connect();}}//服务端2007-12-30 17:33import java.io.*;import java.net.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class Server1 extends JFrame{private JTextArea display;private JTextField enter;JButton sysMessageButton;JButton stopMessageButton,startServerButton;JPanel upPanel;ServerSocket server;Socket socket1;ObjectOutputStream output;ObjectInputStream input;public Server1(){super("服务器端");Container c=getContentPane();enter=new JTextField();setSize(50,20);upPanel=new JPanel();sysMessageButton=new JButton("发送");c.add(sysMessageButton,BorderLayout.EAST);setSize(50,20);stopMessageButton=new JButton("断开连接");c.add(stopMessageButton,BorderLayout.WEST);stopMessageButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ stopService();}});

iOS 中设备之间 socket 传文件应该怎么实现
socket是比较底层的通讯方式,只是建立了一个连接通道,具体上面传输什么样的数据,按照什么格式传输,需要你自己定义。换句话说,你需要自己定义一个文件传输协议。例如,要定义数据包的大小,要定义每个数据包的格式,定义纠错机制,网络中断后如何恢复等等。大文件要拆分成数据包来传输,接收方要把收到的数据包再组装起来。文件名这些信息也做为原始数据的一部分通过数据包传过去,只不过跟文件内容的数据包类型不一样而已。 但是,实现这样一个传输协议是比较麻烦和容易出错的,象传文件这种逻辑比较简单的操作一般没必要在socket层直接操作。iOS提供了CFStream接口,适合文件这种数据流的传输。iOS本身的FTP和HTTP协议栈的实现也是使用CFStream API,而不是直接操作socket的。
sock_stream 是有保障的(即能保证数据正确传送到对方)面向连接的SOCKET,多用于资料(如文件)传送。
sock_dgram 是无保障的面向消息的socket , 主要用于在网络上发广播信息。
SOCK_STREAM是基于TCP的,数据传输比较有保障。SOCK_DGRAM是基于UDP的,专门用于局域网,基于广播
SOCK_STREAM 是数据流,一般是tcp/ip协议的编程,SOCK_DGRAM分是数据抱,是udp协议网络编程
解释一下:
关于UDP
1、UDP协议适用端口分辨运行在同一台设备上的多个应用程序,UDP有不提供数据报分组、组装和不能对数据包进行排序的缺点。
也就是说,当报文发送之后,是无法得知其是否安全完整到达的。
2、在网络质量令人不十分满意的环境下,UDP协议数据包丢失会比较严重。
3、但是由于UDP的特性:它不属于连接型协议,因而具有资源消耗小,处理速度快的优点,所以通常音频、视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。
关于TCP
1、TCP提供端到端、全双工通信;采用字节流方式,如果字节流太长,将其分段;提供紧急数据传送功能。
2、TCP特性:
(1)面向连接的传输; (2)端到端的通信; (3)高可靠性,确保传输数据的正确性,不出现丢失或乱序; (4)全双工方式传输; (5)采用字节流方式,即以字节为单位传输字节序列; (6)紧急数据传送功能。
所以如果你需要传输的数据是准确的,建议采用TCP,也就是sock_stream
如果你传输的是视频音频等数据,丢几个包也无所谓的,可以采用UDP,也就是sock_dgram

socket编程:文件夹的传输
没有别的方法了 传输文件夹只能先遍历文件夹,获取所有文件夹和文件信息 然后在本地建立文件夹,并逐个写文件

本文由 在线网速测试 整理编辑,转载请注明出处。