




已阅读5页,还剩16页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
本文主要介绍如何在C+ Builder中用TServerSocket,TClientSocket来写一个网络间短包,文件传输的程序,这个程序可以支持:1.局域网上的传输。2.局域网与公网的传输(双向传输),在第二篇文章中我将用socket api写一个客户端和服务器,功能和本文中的功能一样。使用通讯协议TCP,这里的客户端和服务器使用的都是阻塞模式-多线程。Client:.h Fileclass ClientThread : public TThreadprivate: AnsiString File; TClientSocket* ClientSocket; TWinSocketStream* WskStream;protected: void _fastcall Execute();public: _fastcall ClientThread(AnsiString IPAddr, WORD Port, AnsiString file);.cpp Filevoid _fastcall ClientThread:Execute() /Send Text or SendFile UINT TimeOut=60000; char buf4096; /char IPAddress32; /GetIPAddress(IPAddress);/IPAddress WskStream = new TWinSocketStream(ClientSocket-Socket, TimeOut); if(Form1-CheckBox1-Checked)/Determine whether to send short package or send file. String S=Form1-TxtEdit-Text; int TxtLen=Form1-TxtEdit-Text.Length(); strncpy(buf,S.c_str(),TxtLen); ClientSocket-Active=true; WskStream-Write(TEXT0,5);/Send Text Flag WskStream-Write(IPAddress,32);/Send IP Address WskStream-Write(buf,TxtLen);/Send Text String WskStream-Write(buf,TxtLen); if(WskStream-WaitForData(TimeOut) buf0=0; FlagBuf0=0; IPAddress0=0; WskStream-Read(FlagBuf,5); WskStream-Read(IPAddress,32); int nSize=0; nSize=WskStream-Read(buf,TxtLen); bufnSize=0; if(!StrPas(buf).IsEmpty() SaveLog(Received a text!); SaveLog(Client:+StrPas(IPAddress)+rnStart Time:+DateTimeToStr(Now(); SaveLog(Text Content:+StrPas(buf); FLASHWINFO FSHINFO; :ZeroMemory(&FSHINFO,sizeof(FLASHWINFO); FSHINFO.cbSize=sizeof(FLASHWINFO); FSHINFO.hwnd=Application-Handle; FSHINFO.dwFlags=FLASHW_TRAY|FLASHW_CAPTION; FSHINFO.uCount=10; FSHINFO.dwTimeout=200; :FlashWindowEx(&FSHINFO); Form1-RecEdit-Lines-Add(Received Length:+String(nSize);Form1-RecEdit-Lines-Add(Received:+StrPas(buf); /SaveLog(Client:+StrPas(IPAddress)+rnEnd Time:+DateTimeToStr(Now(); else int nLen; int hFile; int nSize; char Path255;/Path Buffer char FileName255;/FileName Buffer; char FileExt5;/Extension Buffer char FlagBuf5; static int num=0; AnsiString sFileName=ExtractFileName(File); for(int k=sFileName.Length();k0;k-) if(sFileName.SubString(k,1)=.) sFileName=sFileName.SubString(1,k-1); break; AnsiString sPath=ExtractFilePath(File); AnsiString sExtension=ExtractFileExt(File); strcpy(FileName,sFileName.c_str();/FileName strcpy(Path,sPath.c_str();/Path strcpy(FileExt,sExtension.c_str(); :/Extension try hFile = -1; ClientSocket-Active = true; hFile = FileOpen(File, fmOpenRead); if (hFile != -1) nSize = GetFileSize(HANDLE) hFile, NULL); /Send the Flag WskStream-Write(FILE0,5); /Send the name of directory WskStream-Write(Path,255); /Send the filename WskStream-Write(FileName,255); /Send the extension of file WskStream-Write(FileExt,5); /Send clients IP addresss WskStream-Write(IPAddress,32); /Send the length WskStream-Write(&nSize, 4); /Send the data for(; nSize0; nSize-=nLen) nLen = min(int)sizeof( buf), nSize); nLen = FileRead(hFile, buf, nLen); if (nLenWrite(buf, nLen); FileClose(hFile);/Send Completely /Client is beginning to read data if(WskStream-WaitForData(TimeOut) WskStream-Read(FlagBuf,5); if(WskStream-WaitForData(TimeOut)/Obtain the directorys name WskStream-Read(Path,255); /If the directory obtained from client doesnot exist,the create it if(!DirectoryExists(StrPas(Path) CreateDir(StrPas(Path); /Obtain the FileName if(WskStream-WaitForData(TimeOut) WskStream-Read(FileName,255); /Obtain the extension if(WskStream-WaitForData(TimeOut) WskStream-Read(FileExt,5); /Obtain the clients IPAddress if(WskStream-WaitForData(TimeOut) WskStream-Read(IPAddress,32); AnsiString S=StrPas(Path)+StrPas(FileName)+StrPas(FileExt); buf0=0; strcpy(buf,S.c_str(); while(1) if (FileExists(buf) S=StrPas(Path)+StrPas(FileName)+%03d+StrPas(FileExt); wsprintf(buf, S.c_str(), num); num+; /Created Susscessfully else break; hFile = FileCreate(buf); if (hFile=-1) Application-MessageBox(Failed to create file!,Error,MB_OK+MB_ICONERROR); ClientSocket-Active=false; delete WskStream; Terminate(); return; SaveLog(Received a file:+StrPas(buf); SaveLog(Client:+StrPas(IPAddress)+rnStart Time:+DateTimeToStr(Now(); try DWORD dwTick = GetTickCount(); /Obtain the length if (WskStream-WaitForData( TimeOut) nLen = WskStream-Read( &nSize, 4); if (nLen!=4) nSize = 0; else nSize = 0; /Reading data for(; nSize0 & !Terminated; nSize-=nLen) if (!WskStream-WaitForData( 5000) if (GetTickCount()-dwTick Active=false; break; nLen = WskStream-Read(buf, sizeof(buf); dwTick = GetTickCount(); if (nLen Active=false; :MessageBox(NULL,Read Error,the thread has been terminated!,Error,MB_OK|MB_ICONERROR); break; /Combine the data FileWrite(hFile, buf, nLen); Form1-RecEdit-Lines-Add(You got a file from server,which was saved in +StrPas(Path); SaveLog(Client:+StrPas(IPAddress)+rnEnd Time:+DateTimeToStr(Now(); FLASHWINFO FSHINFO; :ZeroMemory(&FSHINFO,sizeof(FLASHWINFO); FSHINFO.cbSize=sizeof(FLASHWINFO); FSHINFO.hwnd=Application-Handle; FSHINFO.dwFlags=FLASHW_TRAY|FLASHW_CAPTION; FSHINFO.uCount=10; FSHINFO.dwTimeout=200; :FlashWindowEx(&FSHINFO); FileClose(hFile); catch(Exception& e) ClientSocket-Active=false; MessageBox(0, e.Message.c_str(), Error, MB_ICONERROR); catch(Exception& e) ClientSocket-Active=false; :MessageBox(0, e.Message.c_str(), Error, MB_OK|MB_ICONERROR); FileClose(hFile); delete WskStream; / delete ClientSocket;/Begin to send packagevoid _fastcall TForm1:Button1Click(TObject *Sender) int Port; AnsiString Addr; Addr = IPAddr-Text.Trim(); if (Addr.IsEmpty() IPAddr-SetFocus(); Application-MessageBox(Please enter the clients address!,Warning,MB_OK|MB_ICONWARNING); return; try Port = ClientPort-Text.ToInt(); catch(Exception& e) ShowMessage(e.Message); ClientPort-SetFocus(); return; if(CheckBox1-Checked) /Send Text if(TxtEdit-Text.IsEmpty() :MessageBox(0,Please enter the text string which you want to send!,Error,MB_OK+MB_ICONERROR); return; new ClientThread(Addr,Port,); else /Send File if (OpenDialog1-Execute() new ClientThread(Addr, Port, OpenDialog1-FileName); /Begin to send data Server:.h File/My Comments:/At design-time,please place a TServerSocket Component on your form and set its clientype to stThreadBlocking./Server Thread Class/The Server Can not only receives the packages coming from Clients,but also deliver the package to the clients after processing upon the package.class SrvThread : public TServerClientThreadprivate: UINT FTimeOut; TWinSocketStream* WskStream; TThread *pThread;protected: void _fastcall ClientExecute();public: _fastcall SrvThread(TServerClientWinSocket*); _property UINT TimeOut = read=FTimeOut, write=FTimeOut ;void _fastcall SrvThread:ClientExecute() TimeOut = 60000; file:/60 Seconds WskStream = new TWinSocketStream(ClientSocket, TimeOut); file:/Send Text or File char FlagBuf5; char buf4096; char IPAddress32; SMS0=0; RecIPAddr0=0; if(WskStream-WaitForData(TimeOut) file:/Obtain Flag:File or Text WskStream-Read(FlagBuf,5); file:/Save the flag received from clients strcpy(Flag,FlagBuf); if(StrPas(FlagBuf)=TEXT) if(WskStream-WaitForData(TimeOut) WskStream-Read(IPAddress,32); file:/Save the clients IPAddress strcpy(RecIPAddr,IPAddress); if(WskStream-WaitForData(TimeOut) WskStream-Read(buf,4096); file:/Save the short message received from clients strcpy(SMS,buf); SaveLog(Received a text!); SaveLog(Client:+StrPas(IPAddress)+rnStart Time:+DateTimeToStr(Now(); SaveLog(Text Content:+StrPas(SMS); SaveLog(Client:+StrPas(IPAddress)+rnEnd Time:+DateTimeToStr(Now(); Form1-Memo1-Lines-Add(Text Content:+StrPas(buf); FLASHWINFO FSHINFO; :ZeroMemory(&FSHINFO,sizeof(FLASHWINFO); FSHINFO.cbSize=sizeof(FLASHWINFO); FSHINFO.hwnd=Application-Handle; FSHINFO.dwFlags=FLASHW_TRAY|FLASHW_CAPTION; FSHINFO.uCount=10; FSHINFO.dwTimeout=200; :FlashWindowEx(&FSHINFO); if(Form1-adv-Checked)/Automatically Deliver To Client if(StrPas(Flag).IsEmpty() | StrPas(RecIPAddr).IsEmpty() | StrPas(SMS).IsEmpty() Application-MessageBox(You cant deliver because no data are received!,Error,MB_OK+MB_ICONERROR); return; WskStream-Write(FlagBuf,5); WskStream-Write(Form1-ComboBox1-Text.c_str(),32); WskStream-Write(SMS,4096); :Sleep(500);/Delay for 500ms ClientSocket-Close(); if(Form1-spt-Checked)/Automatically deliver to serial port on local computer StrCat(SMS,FlagBuf); StrCat(SMS,Form1-ComboBox1-Text.c_str(); / SaveLog(Write Serial Port +Form1-Port); / SaveLog(Start Time:+DateTimeToStr(Now(); / SaveLog(End Time:+DateTimeToStr(Now(); pThread=new TWriteCommThread(Form1-Port,Form1-BaudRate,(void*)buf,1000); pThread-Terminate(); else if(StrPas(FlagBuf).Pos(GET) file:/GPRS if(WskStream-WaitForData(TimeOut) WskStream-Read(buf,4096); file:/Save the flag to Flag strcpy(Flag,GPRS); file:/Save the frame to SMS strcpy(SMS,buf); file:/Set the destination IP strcpy(RecIPAddr,127.0.0.1); SaveLog(Received a package from GPRS); SaveLog(Start Time:+DateTimeToStr(Now(); SaveLog(StrPas(FlagBuf)+StrPas(buf); SaveLog(End Time:+DateTimeToStr(Now(); Form1-Memo1-Lines-Add(StrPas(FlagBuf)+StrPas(buf); FLASHWINFO FSHINFO; :ZeroMemory(&FSHINFO,sizeof(FLASHWINFO); FSHINFO.cbSize=sizeof(FLASHWINFO); FSHINFO.hwnd=Application-Handle; FSHINFO.dwFlags=FLASHW_TRAY|FLASHW_CAPTION; FSHINFO.uCount=10; FSHINFO.dwTimeout=200; :FlashWindowEx(&FSHINFO); if(Form1-adv-Checked) if(StrPas(Flag).IsEmpty() | StrPas(RecIPAddr).IsEmpty() | StrPas(SMS).IsEmpty() Application-MessageBox(You cant deliver because no data are received!,Error,MB_OK+MB_ICONERROR); return; WskStream-Write(FlagBuf,5); WskStream-Write(Form1-ComboBox1-Text.c_str(),32); WskStream-Write(SMS,4096); :Sleep(500);/ms ClientSocket-Close(); if(Form1-spt-Checked) file:/Automatically deliver to serial port on local computer StrCat(SMS,FlagBuf); StrCat(SMS,Form1-ComboBox1-Text.c_str(); file:/SaveLog(Write Serial Port +Form1-Port); file:/SaveLog(Start Time:+DateTimeToStr(Now(); file:/SaveLog(End Time:+DateTimeToStr(Now(); pThread=new TWriteCommThread(Form1-Port,Form1-BaudRate,(void*)SMS,4096); pThread-Terminate(); else int nLen; int nSize; int hFile; char Path255; file:/Path char FileName255; file:/FileName char FileExt5; file:/Extension static int num=0; file:/Obtain the directorys name if(WskStream-WaitForData(TimeOut) WskStream-Read(Path,255); file:/If the directory obtained from client doesnot exist,the create it if(!DirectoryExists(StrPas(Path) CreateDir(StrPas(Path); file:/Obtain the FileName if(WskStream-WaitForData(TimeOut) WskStream-Read(FileName,255); file:/Obtain the extension if(WskStream-WaitForData(TimeOut) WskStream-Read(FileExt,5); file:/Obtain the clients IPAddress if(WskStream-WaitForData(TimeOut) WskStream-Read(IPAddress,32); file:/Save the clients IPAddress strcpy(RecIPAddr,IPAddress); AnsiString S=StrPas(Path)+StrPas(FileName)+StrPas(FileExt); strcpy(buf,S.c_str(); while(1) if (FileExists(buf) S=StrPas(Path)+StrPas(FileName)+%03d+StrPas(FileExt); wsprintf(buf, S.c_str(), num); num+; file:/Created Susscessfully else break; hFile = FileCreate(buf); if (hFile=-1) Application-MessageBox(Failed to create file on server!,Error,MB_OK+MB_ICONERROR); delete WskStream; Terminate(); return; file:/Save the filename received from clients strncpy(RecFile,buf,255); SaveLog(Received a file:+StrPas(buf); SaveLog(Client:+StrPas(IPAddress)+rnStart Time:+DateTimeToStr(Now(); try DWORD dwTick = GetTickCount(); file:/Obtain the length if (WskStream-WaitForData( TimeOut) nLen = WskStream-Read( &nSize, 4); if (nLen!=4) nSize = 0; else nSize = 0; file:/Reading data for(; nSize0 & !Terminated; nSize-=nLen) if (!WskStream-WaitForData( 5000)
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 云南省云县2025年上半年事业单位公开遴选试题含答案分析
- 河北省易县2025年上半年公开招聘城市协管员试题含答案分析
- 2025年房屋购买与配套设施安装合同
- 2025版铁路客户服务中心客户满意度调查与提升方案合同
- 2025出租居间合同协议书范本:城市综合体租赁服务
- 2025褚之与吴刚的离婚协议书及共同财产分割及子女抚养合同
- 2025年度砼工程劳务分包与进度控制合同
- 2025年度水泥井盖绿色环保认证采购合同约定
- 2025年度文化创意园场地租赁及配套运营管理协议
- 2025年度柴油油品批发与零售价格指数合同
- 新版人教版二年级上册数学全册1-6单元教材分析
- 期中考试考试安排及流程说明
- 铜矿采选工程可行性研究报告
- 2024-2025学年北京市海淀区三年级(下)期末数学试卷
- 大型展会现场安全保障工作方案
- 2025年秋季学期学校全面工作计划
- 收费站文明服务培训
- 战术基础动作课件教学
- 2024年医师定期考核超声专业试题及答案
- 翻越浪浪山共筑新学期成长梦之开学第一课班会课件
- 2025年村级动物防疫员考试题及答案
评论
0/150
提交评论