CB using the socket API to write network communication program

Source: Internet
Author: User
Tags bind bool connect socket resource sleep socket sprintf htons

After reading the Sockcomp.pas on July 4, I decided to use the socket API to write a client and server and support the TCP,UDP protocol at the same time, so I do, and now I post the code (has been debugged)

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"
#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 (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);
};
extern 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_socket=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 buf[4096];
int Nlen;
struct sockaddr_in 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) {
Buf[nlen]= ' ";
txtedit->text= "Received Length:" +string (nlen) + "\ r \ n" +strpas (BUF);
}
Break
Case UDP:
Nlen=recvfrom (m_socket,buf,4096,0, (struct sockaddr*) &from,&nlength);
if (nlen>0) {
Buf[nlen]= ' ";
txtedit->text= "Received Length:" +string (nlen) + "\ r \ n" +strpas (BUF);
}
Break
}
Break
Case Fd_close:
Closesocket (M_socket);
Break
}
}
void __fastcall Tlanform::button1click (tobject *sender)
{
Char sztmp[256],buf[4096];
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) {
:: MessageBox (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-&GT;ITEMINDEX)
{
Case 0:
M_PROTOCOL=TCP;
Break
Case 1:
M_PROTOCOL=UDP;
Break
}
if (Txtedit->text.isempty ()) {
:: MessageBox (0, "Please enter the text of your want to send!", "Error", mb_ok+mb_iconerror);
return;}
Initialize WinSocket
Wsadata Wsadata;
:: ZeroMemory (&wsadata,sizeof (wsadata));
WORD Version=makeword (2,0);
if (:: WSAStartup (Version,&wsadata)) {
sprintf (Sztmp, "Failed to initial Winsock Enviroment!,error",:: no:%d ());
return;}
Obtain the active connection
Char computername[255];
GetHostName (computername,255);
struct hostent* he=gethostbyname (ComputerName);
if (!he) {
sprintf (Sztmp, "Failed to get information to host!", "Error", mb_ok+mb_iconerror);
:: WSACleanup ();
Return
}
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, "Failed to create a new Socket!,error no:%d",:: WSAGetLastError ());
:: MessageBox (0,sztmp, "Error", mb_ok+mb_iconerror);
:: WSACleanup ();
Return
}
Bind socket
struct SOCKADDR_IN client;
unsigned long nclient;
memcpy (&nclient,he->h_addr_list[0],sizeof (int));
if (Nclient==inaddr_none) {
sprintf (Sztmp, "Failed to obtain" of 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;
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;}
Connect socket
struct sockaddr_in to;
To.sin_family=af_inet;
To.sin_port=htons (M_port);
To.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, "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;}
}
Send data
int Nlen=txtedit->text.length ();
if (nlen>4096) {
sprintf (sztmp, "the buffer is too size to send,it shoud ' not being 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 <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 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
Public
__fastcall tcommunication (SOCKET m_socket,bool createsuspended);
__fastcall ~tcommunication ();
Protected
virtual void __fastcall Execute ();
};
Class Tlistenthread:public TThread//listen Thread
{
Private
Wsadata Wsadata;
struct SOCKADDR_IN server;
Fd_set FDS;
UINT M_port;
PROTO M_protocol;
Char Sztmp[256];//error message
Public
SOCKET M_socket;
void __fastcall doerror ();
void __fastcall initsocket ();
void __fastcall createlistensocket ();
void __fastcall setlistensocket ();
void __fastcall bindlistensocket ();
void __fastcall listensocket ();
Public
__fastcall tlistenthread (PROTO m_protocola,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 "*.DFM"
Tpstnform *pstnform;
Tlistenthread *pthread=0;
CLASS tcommunication for tcp****************************************************
__fastcall tcommunication::tcommunication (SOCKET m_socket,bool createsuspended): TThread (FALSE)
{
M_acceptsocket=m_socket;
Sztmp[0]= ' ";
Freeonterminate=true;
}
__fastcall tcommunication::~tcommunication ()
{
Closesocket (M_acceptsocket);
}
void __fastcall Tcommunication::execute ()
{
Char buf[4096];
int nsize=0;
Nsize=recv (M_acceptsocket, (char far*) buf,4096,0);
if (nsize>0)
{
Buf[nsize]= ' ";
Display
Pstnform->memo1->lines->add ("Received Length:" +string (nsize));
Pstnform->memo1->lines->add ("Received:" +strpas (BUF));
Deliver
:: Sleep (100);
Send (m_acceptsocket,buf,nsize,0);
}
}
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_protocola;
Sztmp[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_PROTOCOL=TCP;
Sztmp[0]= ' ";
:: ZeroMemory (&wsadata,sizeof (wsadata));
:: ZeroMemory (&server,sizeof (struct sockaddr_in));
}
void __fastcall Tlistenthread::D oerror ()
{
if (m_socket!=invalid_socket) closesocket (M_socket);
WSACleanup ();
Return
}
void __fastcall Tlistenthread::initsocket ()
{
WORD Version=makeword (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=socket (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!");
:: MessageBox (0,sztmp, "Error", mb_ok+mb_iconerror);
Doerror ();
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,sol_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,sizeof (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",:: WSAGetLastError ());
:: MessageBox (0,sztmp, "Error", mb_ok+mb_iconerror);
Doerror ();
Return
}
Determine whether there is any connection
Fd_zero (&fds);
Fd_set (M_socket,&fds);
}
void __fastcall Tlistenthread::execute ()
{
Char buf[4096];
struct sockaddr_in from; For UDP
int nlen=sizeof (from), nsize=0; 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) {
Buf[nsize]= ' ";
Pstnform->memo1->lines->add ("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_socket, (struct sockaddr*) &client,&nlength);
if (m_acceptsocket==invalid_socket) {
sprintf (Sztmp, "Failed to execute Accept,error no:%d",:: WSAGetLastError ());
:: MessageBox (0,sztmp, "Error", mb_ok+mb_iconerror);
Doerror ();
Terminate ();
Return
}
Tcommunication *pcthread=new tcommunication (m_acceptsocket,false);
Pcthread->terminate ();
Pcthread->waitfor ();
}
}
pstnform*********************************************//
__fastcall tpstnform::tpstnform (tcomponent* Owner)
: Tform (Owner)
{
}
void __fastcall Tpstnform::button1click (tobject *sender)
{
Close ();
}
void __fastcall Tpstnform::button2click (tobject *sender)
{
if (pThread) {
Pthread->suspend ();
Pthread->terminate ();
Delete PThread;
Pthread=0;
}
UINT M_port;
Try
{
M_port=port->text.toint ();
}
catch (Exception &e)
{
:: MessageBox (0,e.message.c_str (), "Error", mb_ok+mb_iconerror);
Return
}
PROTO M_protocol;
Switch (PROT-&GT;ITEMINDEX)
{
Case 0:
M_PROTOCOL=TCP;
Break
Case 1:
M_PROTOCOL=UDP;
Break
Default
Break
}
Pthread=new Tlistenthread (M_protocol,m_port,false);
Pthread->terminate ();
}
void __fastcall tpstnform::formcreate (tobject *sender)
{
:: SendMessage (prot->handle,cb_setcursel,0,1);
}
void __fastcall Tpstnform::formdestroy (tobject *sender)
{
if (pThread) {
Pthread->suspend ();
Pthread->terminate ();}
}

The above code, you can be based on their own needs and for their own applications, in the data processing to improve on it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.