在CBuilder中用socketapi來寫網(wǎng)絡(luò)通訊程序_第1頁
在CBuilder中用socketapi來寫網(wǎng)絡(luò)通訊程序_第2頁
在CBuilder中用socketapi來寫網(wǎng)絡(luò)通訊程序_第3頁
在CBuilder中用socketapi來寫網(wǎng)絡(luò)通訊程序_第4頁
在CBuilder中用socketapi來寫網(wǎng)絡(luò)通訊程序_第5頁
已閱讀5頁,還剩1頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、看完sockcomp.pas后,我決定用socket api來寫一個客戶端和服務器并且同時支持TCP,UDP協(xié)議,于是我就去做,現(xiàn)將代碼貼出來(已調(diào)試通過) Socket api Client: #ifndef UDPClientH #define UDPClientH #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <stdio.h> #include "CCEdit.h

2、" #define WM_SOCK WM_USER+100 class TLANForm : public TForm _published: / IDE-managed Components TEdit *Port; TLabel *Label1; TLabel *Label2; TComboBox *Prot; TButton *Button1; TLabel *Label3; TEdit *Addr; TCCEdit *TxtEdit; void _fastcall FormCreate(TObject *Sender); void _fastcall Button1Click

3、(TObject *Sender); void _fastcall FormDestroy(TObject *Sender); private: / User declarations void _fastcall OnRecv(TMessage &Message); public: / User declarations _fastcall TLANForm(TComponent* Owner); BEGIN_MESSAGE_MAP VCL_MESSAGE_HANDLER(WM_SOCK,TMessage,OnRecv); END_MESSAGE_MAP(TForm); ; exte

4、rn PACKAGE TLANForm *LANForm; #endif .cpp File #include <vcl.h> #pragma hdrstop #include "UDPClient.h" #include "WinSock.h" #pragma package(smart_init) #pragma link "CCEdit" #pragma resource "*.dfm" TLANForm *LANForm; enum PROTO TCP=0,UDP=1; SOCKET m_Soc

5、ket=INVALID_SOCKET; PROTO m_Protocol=TCP; _fastcall TLANForm:TLANForm(TComponent* Owner) : TForm(Owner) void _fastcall TLANForm:FormCreate(TObject *Sender) :SendMessage(Prot->Handle,CB_SETCURSEL,0,0); void _fastcall TLANForm:OnRecv(TMessage &Message) char buf4096; int nLen; struct sockaddr_in

6、 from; int nLength=sizeof(struct sockaddr_in); switch(WSAGETSELECTEVENT(Message.LParam) case FD_READ: switch(m_Protocol) case TCP: nLen=recv(m_Socket,buf,4096,0); if(nLen>0) bufnLen='0' TxtEdit->Text="Received Length:"+String(nLen)+"rn"+StrPas(buf); break; case UDP:

7、 nLen=recvfrom(m_Socket,buf,4096,0,(struct sockaddr*)&from,&nLength); if(nLen>0) bufnLen='0' TxtEdit->Text="Received Length:"+String(nLen)+"rn"+StrPas(buf); break; break; case FD_CLOSE: closesocket(m_Socket); break; void _fastcall TLANForm:Button1Click(TObje

8、ct *Sender) char szTmp256,buf4096; int nSize=0; UINT m_Port; AnsiString addr; addr=Addr->Text.Trim(); if(addr.IsEmpty() :MessageBox(0,"Please enter the server IP!","Error",MB_OK+MB_ICONERROR); return; unsigned long nAddr=inet_addr(addr.c_str(); if(nAddr=INADDR_NONE) :MessageBo

9、x(0,"Bad Internet IP!","Error",MB_OK+MB_ICONERROR); return; try m_Port=Port->Text. ToInt(); catch(Exception &e) :MessageBox(0,e.Message.c_str(),"Error",MB_OK+MB_ICONERROR); return; switch(Prot->ItemIndex) case 0: m_Protocol=TCP; break; case 1: m_Protocol=UDP;

10、break; if(TxtEdit->Text.IsEmpty() :MessageBox(0,"Please enter the text you want to send!","Error",MB_OK+MB_ICONERROR); return; file:/Initialize Winsocket WSAData wsaData; :ZeroMemory(&wsaData,sizeof(WSAData); WORD version=MAKEWORD(2,0); if(:WSAStartup(version,&wsaData)

11、 sprintf(szTmp,"Failed to initial winsock enviroment!,error no:%d",:WSAGetLastError(); return; file:/Obtain the active connection char ComputerName255; gethostname(ComputerName,255); struct hostent* he=gethostbyname(ComputerName); if(!he) sprintf(szTmp,"Failed to get information to ho

12、st!","Error",MB_OK+MB_ICONERROR); :WSACleanup(); return; file:/create new socket m_Socket=INVALID_SOCKET; switch(m_Protocol) case TCP: m_Socket=socket(AF_INET,SOCK_STREAM,0); break; case UDP: m_Socket=socket(AF_INET,SOCK_DGRAM,0); break; if(m_Socket=INVALID_SOCKET) sprintf(szTmp,"

13、;Failed to create a new socket!,error no:%d",:WSAGetLastError(); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); :WSACleanup(); return; file:/bind socket struct sockaddr_in client; unsigned long nClient; memcpy(&nClient,he->h_addr_list0,sizeof(int); if(nClient=INADDR_NONE) spr

14、intf(szTmp,"Failed to obtain the local machine's IP!","Error",MB_OK+MB_ICONERROR); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); closesocket(m_Socket); :WSACleanup(); return; client.sin_family=AF_INET; client.sin_port=0; client.sin_addr.S_un.S_addr=(int)nClient;

15、if(bind(m_Socket,(struct sockaddr*)&client,sizeof(struct sockaddr) sprintf(szTmp,"Failed to bind socket!","Error",MB_OK+MB_ICONERROR); closesocket(m_Socket); :WSACleanup(); return; file:/connect socket struct sockaddr_in To; To.sin_family=AF_INET; To.sin_port=htons(m_Port); T

16、o.sin_addr.S_un.S_addr=(int)nAddr; fd_set FDSET; FD_ZERO(&FDSET); FD_SET(m_Socket,&FDSET); if(m_Protocol=TCP) if(connect(m_Socket,(struct sockaddr*)&To,sizeof(struct sockaddr) sprintf(szTmp,"Failed to connect the object!,error no:%d",:WSAGetLastError(); :MessageBox(0,szTmp,&quo

17、t;Error",MB_OK+MB_ICONERROR); closesocket(m_Socket); :WSACleanup(); return; int nError=select(1,0,&FDSET,0,0); if(nError<=0) sprintf(szTmp,"Failed to select socket!,error no:%d",:WSAGetLastError(); closesocket(m_Socket); :WSACleanup(); return; file:/Sen d data int nLen=TxtEdit-

18、>Text.Length(); if(nLen>4096) sprintf(szTmp,"The buffer is too size to send,it shoud not be more than 4096 bytes!"); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); closesocket(m_Socket); :WSACleanup(); return; strncpy(buf,TxtEdit->Text.c_str(),nLen); switch(m_Protocol)

19、 case TCP: nSize=send(m_Socket,buf,nLen,0); file:/ShowMessage(nSize); break; case UDP: nSize=sendto(m_Socket,buf,nLen,0,(struct sockaddr*)&To,sizeof(struct sockaddr); file:/ShowMessage(nSize); break; if(:WSAAsyncSelect(m_Socket,Handle,WM_SOCK,FD_READ|FD_CLOSE) sprintf(szTmp,"Failed to regis

20、ter socket event!,error no:%d",:WSAGetLastError(); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); closesocket(m_Socket); :WSACleanup(); return; void _fastcall TLANForm:FormDestroy(TObject *Sender) closesocket(m_Socket); :WSACleanup(); Socket api Server: .h File #ifndef UDPServerH #d

21、efine UDPServerH #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <stdio.h> #include "WinSock.h" /*#define WM_SOCKET WM_USER+1000 #define INITSOCKETSUCCESS 0 #define INITSOCKETFAILURE 1 #define CREATELISTENSO

22、CKETSUCCESS 2 #define CREATELISTENSOCKETFAILURE 3 #define SETLISTENSOCKETSUCCESS 4 #define SETLISTENSOCKETFAILURE 5 #define BINDLISTENSOCKETSUCCESS 6 #define BINDLISTENSOCKETFAILURE 7 #define LISTENSOCKETSUCCESS 8 #define LISTENSOCKETFAILURE 9 #define ACCEPTSOCKETSUCCESS 10 #define ACCEPTSOCKETFAILU

23、RE 11 */ class TPSTNForm : public TForm _published: / IDE-managed Components TEdit *Port; TLabel *Label1; TMemo *Memo1; TButton *Button1; TButton *Button2; TLabel *Label2; TComboBox *Prot; void _fastcall Button1Click(TObject *Sender); void _fastcall Button2Click(TObject *Sender); void _fastcall Form

24、Create(TObject *Sender); void _fastcall FormDestroy(TObject *Sender); private: / User declarations public: / User declarations _fastcall TPSTNForm(TComponent* Owner); ; enum PROTO TCP,UDP; class TCommunication:public TThread file:/Communication Thread private: SOCKET m_AcceptSocket; char szTmp256;/E

25、RROR MESSAGE public: _fastcall TCommunication(SOCKET m_Socket,bool CreateSuspended); _fastcall TCommunication(); protected: virtual void _fastcall Execute(); ; class TListenThread:public TThread file:/Listen Thread private: WSAData wsaData; struct sockaddr_in server; fd_set FDS; UINT m_Port; PROTO m

26、_Protocol; char szTmp256;/Error Message public: SOCKET m_Socket; void _fastcall DoError(); void _fastcall InitSocket(); void _fastcall CreateListenSocket(); void _fastcall SetListenSocket(); void _fastcall BindListenSocket(); void _fastcall Liste nSocket(); public: _fastcall TListenThread(PROTO m_Pr

27、otocolA,UINT m_PortA,bool CreateSuspended); virtual _fastcall TListenThread(); protected: virtual void _fastcall Execute(); ; extern PACKAGE TPSTNForm *PSTNForm; #endif .cpp File #include <vcl.h> #pragma hdrstop #include "UDPServer.h" #pragma package(smart_init) #pragma resource &quo

28、t;*.dfm" TPSTNForm *PSTNForm; TListenThread *pThread=0; file:/*CLASS TCommunication For TCP* _fastcall TCommunication:TCommunication(SOCKET m_Socket,bool CreateSuspended):TThread(FALSE) m_AcceptSocket=m_Socket; szTmp0='0' FreeOnTerminate=true; _fastcall TCommunication:TCommunication() /

29、 closesocket(m_AcceptSocket); void _fastcall TCommunication:Execute() char buf4096; int nSize=0; nSize=recv(m_AcceptSocket,(char FAR*)buf,4096,0); if(nSize>0) bufnSize='0' file:/Display PSTNForm->Memo1->Lines->Add("Received Length:"+String(nSize); PSTNForm->Memo1->

30、;Lines->Add("Received:"+StrPas(buf); file:/Deliver :Sleep(100); send(m_AcceptSocket,buf,nSize,0); file:/*CLASS TListenThread* _fastcall TListenThread:TListenThread(PROTO m_ProtocolA,UINT m_PortA,bool CreateSuspended):TThread(FALSE) m_Socket=INVALID_SOCKET; m_Port=m_PortA; m_Protocol=m_P

31、rotocolA; szTmp0='0' :ZeroMemory(&wsaData,sizeof(WSAData); :ZeroMemory(&server,sizeof(struct sockaddr_in); FreeOnTerminate=TRUE;/Automatically delete while terminating. _fastcall TListenThread:TListenThread() closesocket(m_Socket); :WSACleanup(); m_Socket=INVALID_SOCKET; m_Port=0; m_

32、Protocol=TCP; szTmp0='0' :ZeroMemory(&wsaData,sizeof(WSAData); :ZeroMemory(&server,sizeof(struct sockaddr_in); void _fastcall TListenThread:DoError() if(m_Socket!=INVALID_SOCKET) closesocket(m_Socket); WSACleanup(); return; void _fastcall TListenThread:InitSocket() WORD version=MAKEW

33、ORD(2,0); if(:WSAStartup(version,&wsaData) sprintf(szTmp,"Failed to intiailize socket,error no:%d",:WSAGetLastError(); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); DoError(); return; void _fastcall TListenThread:CreateListenSocket() switch(m_Protocol) case UDP: m_Socket=s

34、ocket(AF_INET,SOCK_DGRAM,0); break; case TCP: m_Socket=socket(AF_INET,SOCK_STREAM,0); break; default: sprintf(szTmp,"Error protocol!"); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); DoError(); break; if(m_Socket=INVALID_SOCKET) sprintf(szTmp,"Failed to create socket!"

35、;); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); D oError(); return; void _fastcall TListenThread:SetListenSocket() server.sin_family=AF_INET; server.sin_port=htons(m_Port); server.sin_addr.S_un.S_addr=INADDR_ANY; int NewOpenType=SO_SYNCHRONOUS_NONALERT; if(setsockopt(INVALID_SOCKET,SO

36、L_SOCKET,SO_OPENTYPE,(char*)&NewOpenType,4) sprintf(szTmp,"Set socket option error,error no:%d",:WSAGetLastError(); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); DoError(); return; void _fastcall TListenThread:BindListenSocket() if(bind(m_Socket,(sockaddr*)&server,size

37、of(struct sockaddr_in) sprintf(szTmp,"Failed to bind socket,error no:%d",:WSAGetLastError(); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); DoError(); return; void _fastcall TListenThread:ListenSocket() if(listen(m_Socket,SOMAXCONN) sprintf(szTmp,"listen error,error no:%d&

38、quot;,:WSAGetLastError(); :MessageBox(0,szTmp,"Error",MB_OK+MB_ICONERROR); DoError(); return; file:/Determine whether there is any connection FD_ZERO(&FDS); FD_SET(m_Socket,&FDS); void _fastcall TListenThread:Execute() char buf4096; struct sockaddr_in from; file:/for UDP int nLen=s

39、izeof(from),nSize=0; file:/for UDP InitSocket(); CreateListenSocket(); SetListenSocket(); BindListenSocket(); if(m_Protocol=UDP) while(!Terminated) int nSize=recvfrom(m_Socket,buf,4096,0,(struct sockaddr*)&from,&nLen); if(nSize>0) bufnSize='0' PSTNForm->Memo1->Lines->Add(

40、"Received Length:"+String(nSize); PSTNForm->Memo1->Lines->Add("Received:"+StrPas(buf); :Sleep(100); sendto(m_Socket,buf,nSize,0,(struct sockaddr*)&from,sizeof(struct sockaddr_in); else return; ListenSocket(); struct sockaddr_in client; int nLength=sizeof(struct sockaddr_in); while(!Terminated) int nError=select(1,&FDS,0,0,0); if(nError<=0) Terminate(); SOCKET m_AcceptSocket=accept(m_

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論