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;}
}
//Send data
int nLen=TxtEdit->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)
{
case TCP:
nSize=send(m_Socket,buf,nLen,0);
//ShowMessage(nSize);
break;
case UDP:
nSize=sendto(m_Socket,buf,nLen,0,(struct sockaddr*)&To,sizeof(struct sockaddr));
//ShowMessage(nSize);
break;
}
if(::WSAAsyncSelect(m_Socket,Handle,WM_SOCK,FD_READ|FD_CLOSE)){
sprintf(szTmp,"Failed to register 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
#define UDPServerH
#include
#include
#include
#include
#include
#include "WinSock.h"
/*#define WM_SOCKET WM_USER+1000
#define INITSOCKETSUCCESS 0
#define INITSOCKETFAILURE 1
#define CREATELISTENSOCKETSUCCESS 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 ACCEPTSOCKETFAILURE 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 FormCreate(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 //Communication Thread
{
private:
SOCKET m_AcceptSocket;
char szTmp[256];//ERROR MESSAGE
责任编辑:小草