Socket communication between cpp Csharp code

Socket communication between cpp Csharp code

Socket communication between cpp Csharp code

C++ code:

//Server.h

//TCP server class that handles multiple connection.
class Server
{
private:
//Socket FD of server
CTCPServerSocket serverSocketFd;
//Forwarder Sockets
CTCPClientSocket *m_forwarder1;
bool m_forwardwer1Connected;
//List of pointers of connected client
vector<CTCPSocket*> m_clientPtr;
vector<S32> m_pktsRecv;
//FD set to mask FD of clients connected and server
fd_set m_masterFdSet;
//Maximum socket fd
S32 m_max_fd;
//IP of server
S8* IP;
//port of server
U32 serverPort;
//mutex to protect data consistency
pthread_mutex_t socket_mutex;
//mutex to prevent sending simultaneously
pthread_mutex_t send_mutex;

//wait for receiving data on connected clients and new connection on server
void Receiver();
//receive data on client
void ClientReceiver(S32);
//accept connection of client
void Acceptor();
//close connection
void CloseConnection(fd_set*);
//close client connection
void CloseConnection(S32);
//add connection to the connected client list
void addConnection(CTCPSocket*);
//update maximum socket fd
void updateMaxFd();
//handle data received from client
void handleData(S8*,S32);
public:
//default constructor
//initialize server IP & port and worker queue
S32 init(S8 *,U32 portNo);
//intialize server for listening for connections
void ServerInitializer();
//send data to client
void ServerSenderMethod(S8 * Buffer,S32 pduLen,CTCPSocket *sock_fd);
};

//TCP server thread
void *ServerThread(void *arg);
Server();
//destructor
Server.cpp

/*
This is a definition of TCP server class that handles multiple connection.*/

//header files – internal
#include “Server.h”
#include <cstring>
#include <cstdlib>

Server::Server()
{
// initialize all member variable with initial value
IP=NULL;
pthread_mutex_init(&send_mutex, NULL);
pthread_mutex_init(&socket_mutex, NULL);
}
Server::~Server()
{
// destructor

}
//initialize server IP and port

S32 Server::init(S8* p_IP,U32 portNo)
{
pthread_t thr_id;
S32 ret_val=0;
m_forwardwer1Connected = false;
//Create TCP-SERVER thread
serverPort = portNo;
IP = p_IP;
ret_val = pthread_create(&thr_id, NULL,ServerThread,(void*)this);
if(ret_val==FAILURE)
{
return FAILURE;
}

return SUCCESS;
}
//TCP server thread

void* ServerThread(void *arg)
{
Server* tcpServer = (Server*)arg;
tcpServer->ServerInitializer();

return 0;
}
//accept connection of client

void Server::Acceptor()
{
CTCPSocket * l_newClient = new CTCPSocket();
if ((l_newClient->mSockfd = serverSocketFd.Accept ()) < 0) // accept new connection
{
delete l_newClient;
}
else
{
addConnection(l_newClient);
}
}
//add connection to the connected client list

void Server::addConnection(CTCPSocket* p_newClient)
{
pthread_mutex_lock(&socket_mutex);
m_clientPtr.push_back(p_newClient);
m_pktsRecv.push_back(0);
FD_SET(p_newClient->mSockfd,&m_masterFdSet);
if(p_newClient->mSockfd >m_max_fd)
m_max_fd = p_newClient->mSockfd;
pthread_mutex_unlock(&socket_mutex);
}
//wait for receiving data on connected clients and new connection on server

void Server::Receiver()
{
fd_set readfds;
S32 max_fd = -1,ret_val;
U32 i;
CTCPSocket *l_clientSock;
struct timeval timeout;

FD_ZERO (&readfds);
FD_ZERO (&m_masterFdSet);
m_max_fd = serverSocketFd.mSockfd;
FD_SET(serverSocketFd.mSockfd,&m_masterFdSet);

while(1)
{

max_fd = m_max_fd;
readfds = m_masterFdSet;
timeout.tv_sec = 20;
timeout.tv_usec = 0;
if(!FD_ISSET(serverSocketFd.mSockfd,&readfds))
{
FD_SET(serverSocketFd.mSockfd,&m_masterFdSet);
}

if ((ret_val = select ((max_fd + 1), &readfds, NULL, NULL, (&timeout))) <= 0) // select on client fd.
{
if (ret_val == 0)
{
continue;
}
else if (ret_val < 0)
{
if (errno == EINTR)
{
CloseConnection(&readfds);
continue;
}
else
{

exit(0);
}
}
}
else
{
if(FD_ISSET(serverSocketFd.mSockfd,&readfds))
{
//FD_CLR (serverSocketFd.mSockfd,&readfds);
Acceptor();
}
for(i=0;i<m_clientPtr.size();i++)
{
l_clientSock = m_clientPtr[i];
if(l_clientSock)
{
if( l_clientSock->mSockfd!=-1 && FD_ISSET(l_clientSock->mSockfd,&readfds) )
{
FD_CLR (l_clientSock->mSockfd,&readfds);

ClientReceiver(i);
}
}
else
{

pthread_mutex_lock(&socket_mutex);
m_clientPtr.erase( m_clientPtr.begin()+i);
m_pktsRecv.erase(m_pktsRecv.begin()+i);
updateMaxFd();
pthread_mutex_unlock(&socket_mutex);
}
}
}
}
}
//receive data on client

void Server::ClientReceiver(S32 p_clientIndex)
{

CTCPSocket *l_clientSock;
S8 Buffer[BUFFER_SIZE];
S32 recv_len;
l_clientSock = m_clientPtr[p_clientIndex];

memset(Buffer,’\0′,BUFFER_SIZE);

recv_len= l_clientSock->Receive (l_clientSock->mSockfd,Buffer,BUFFER_SIZE-1);
if (recv_len == FAILURE )
{
CloseConnection(p_clientIndex);
return ;
}

if(!( recv_len > BUFFER_SIZE))
{
m_pktsRecv[p_clientIndex]++;
// handle the buffer received
handleData(Buffer,p_clientIndex);

}
else
{
CloseConnection(p_clientIndex);
return;
}

}

void Server::CloseConnection(fd_set* p_readFdSet)
{

CTCPSocket *l_clientSock;
pthread_mutex_lock(&socket_mutex);
for(U32 i=0;i<m_clientPtr.size();i++)
{
l_clientSock = m_clientPtr[i];
if(l_clientSock)
{
if( l_clientSock->mSockfd!=-1 && FD_ISSET(l_clientSock->mSockfd,p_readFdSet) )
{
l_clientSock->Close();
delete l_clientSock;

m_clientPtr.erase(m_clientPtr.begin()+i);
m_pktsRecv.erase(m_pktsRecv.begin()+i);
break;
}
}
else
{
m_clientPtr.erase(m_clientPtr.begin()+i);
m_pktsRecv.erase(m_pktsRecv.begin()+i);
}

}
updateMaxFd();
pthread_mutex_unlock(&socket_mutex);
}

void Server::CloseConnection(S32 p_clientIndex)
{

CTCPSocket *l_clientSock;
pthread_mutex_lock(&socket_mutex);
l_clientSock = m_clientPtr[p_clientIndex];
if(l_clientSock)
{
if( l_clientSock->mSockfd!=-1 )
{
FD_CLR (l_clientSock->mSockfd,&m_masterFdSet);
l_clientSock->Close();
delete l_clientSock;
}
}
m_clientPtr.erase(m_clientPtr.begin()+p_clientIndex);
m_pktsRecv.erase(m_pktsRecv.begin()+p_clientIndex);
updateMaxFd();
pthread_mutex_unlock(&socket_mutex);
}
//update maximum socket fd

void Server::updateMaxFd()
{

S32 l_MaxFd=-1;
for(U32 i=0;i<m_clientPtr.size();i++)
{
if(m_clientPtr[i]->mSockfd>l_MaxFd)
l_MaxFd = m_clientPtr[i]->mSockfd;
}
if( l_MaxFd==-1)
m_max_fd = serverSocketFd.mSockfd;
else
m_max_fd = l_MaxFd;

}
//handle data received from client

void Server::handleData(S8* p_buffer,S32 p_clientIndex)
{

Config& l_configInstance = Config::getInstance();
S32 ret_val=SUCCESS;
if(!m_forwardwer1Connected)
{
m_forwarder1 = new CTCPClientSocket();
if(m_forwarder1->Connect((S8*)l_configInstance.getStringType(Config::m_forwarderIp1).c_str(),l_configInstance.getS32Type(Config::m_forwarderPort1))!=SUCCESS)
{

delete m_forwarder1;
}
else
{
m_forwardwer1Connected = true;
ret_val=m_forwarder1->Send(p_buffer,strlen(p_buffer));
}
}
else
ret_val=m_forwarder1->Send(p_buffer,strlen(p_buffer));
if(ret_val==FAILURE)
{
m_forwarder1->Close();
m_forwardwer1Connected = false;
delete m_forwarder1;
}
}
// intialize server for listening for connections

void Server::ServerInitializer()
{

if(FAILURE == serverSocketFd.Create())
{
exit(0);
}

while((serverSocketFd.Bind(serverPort,IP,true, false)) != SUCCESS) // Binding as server on port
{
exit(0);
}

if((serverSocketFd.Listen()) != SUCCESS) // Listening for new connections
{
exit(0);
}

while(1)
{
Receiver();
}
}

//send data to client
void Server::ServerSenderMethod(S8 * Buffer,S32 pduLen,CTCPSocket *sock_fd)
{
S32 ret_val;

ret_val=sock_fd->Send(sock_fd->mSockfd,Buffer,pduLen);
if(ret_val==FAILURE)
{
pthread_mutex_unlock(&send_mutex);
return;
}
pthread_mutex_unlock(&send_mutex);

}

// – This is a definition of Socket class. It is general implementation of Berkeley sockets for making TCP/UDP connections

//Socket.cpp
#include “Socket.h”
#include <cstring>

void sigchld_handler(int s)
{
while(wait(NULL) > 0);
}

Default constrcutor of base socket class

CSocket::CSocket ():mSockfd (-1)
{
memset (&mAddr, 0, sizeof (mAddr));
struct sigaction sa;
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror(“sigaction”);
exit(1);
}

}

CSocket::~CSocket ()
{
close (mSockfd);
}

//Binds a TCP socket to IP and port
S16 CSocket::Bind (S32 nPort,S8* p_IP, bool htonsFlag, bool loopback_flag)
{
S32 iRet;
mAddr.sin_family = AF_INET;

if (loopback_flag == true)
mAddr.sin_addr.s_addr = inet_addr (“127.0.0.1”);
else
{
mAddr.sin_addr.s_addr = inet_addr (p_IP);
}

if (htonsFlag == true)
mAddr.sin_port = htons (nPort);
else
mAddr.sin_port = nPort;

iRet = bind (mSockfd, (struct sockaddr *) &mAddr, sizeof (mAddr));
if (iRet != 0)
{
perror (“error no in bind'”);
return FAILURE;
}
inet_ntoa (mAddr.sin_addr),(int)nPort);
return SUCCESS;
}

//Set Socket Fd to Non-Blocking
S16 CSocket::SetNonBlocking (const S16 bFlag)
{
S32 Opts;

Opts = fcntl (mSockfd, F_GETFL);

if (Opts < 0)
{
return FAILURE;
}

if (bFlag)
Opts = (Opts | O_NONBLOCK);
else
Opts = (Opts & ~O_NONBLOCK);

fcntl (mSockfd, F_SETFL, Opts);
return SUCCESS;
}
// Close Socket Fd
void CSocket::Close ()
{
if (-1 == shutdown (mSockfd, 2))
{

switch(errno)
{
case EBADF:
break;
case EINVAL:

break;
case ENOTCONN:
break;
case ENOTSOCK:

break;
case ENOBUFS:
break;
default: break;
}
}
close (mSockfd);
mSockfd = -1;
}

// TCP Socket class default Constructor
CTCPSocket::CTCPSocket ()
{
status = -1;
}
CTCPSocket::~CTCPSocket ()
{
}
// Create TCP Socket and set various socket options

S16 CTCPSocket::Create ()
{
S32 i = 1;
struct timeval snd_timeout;
snd_timeout.tv_sec = 0;
snd_timeout.tv_usec = 10;

U32 recv_buf_size = 0;
U32 snd_buf_size = 0;

recv_buf_size = TCP_BUFF_SIZE * 1024;
snd_buf_size = TCP_BUFF_SIZE * 1024;
mSockfd = socket (AF_INET, SOCK_STREAM, 0);

if (mSockfd < 0)
{
return FAILURE;
}
if (setsockopt(mSockfd, SOL_SOCKET, SO_REUSEADDR, (const char *) &i, sizeof (i)) != 0)
{

close (mSockfd);
mSockfd = -1;
return FAILURE;
}

if (setsockopt(mSockfd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size,(int) sizeof (int)) != 0)
{

close (mSockfd);
mSockfd = -1;
return FAILURE;
}
if (setsockopt(mSockfd, SOL_SOCKET, SO_SNDBUF, (char *) &snd_buf_size,(int) sizeof (int)) != 0)
{
close (mSockfd);
mSockfd = -1;
return FAILURE;
}

S32 sockoption = 1;
if (setsockopt (mSockfd, IPPROTO_TCP, TCP_NODELAY, (char *) &sockoption, sizeof(int)) != 0)
{

close (mSockfd);
mSockfd = -1;
return FAILURE;
}

if (setsockopt(mSockfd, SOL_SOCKET, SO_SNDTIMEO, (struct timeval *) &snd_timeout,(int) sizeof (struct timeval)) != 0)
{

close (mSockfd);
mSockfd = -1;
return FAILURE;
}
return SUCCESS;

}

// Create UDP Socket
S16 CUDPSocket::Create ()
{
mSockfd = socket (AF_INET, SOCK_DGRAM, 0);
if (mSockfd < 0)
{
return FAILURE;
}
return SUCCESS;
}
// Set IP and port of UDP Socket
void CUDPSocket::SetHostnPort (S8 * host, S32 nPort, bool htonsFlag)
{
mClientAddr.sin_family = AF_INET;
mClientAddr.sin_addr.s_addr = inet_addr (host);

if (htonsFlag == true)
mClientAddr.sin_port = htons (nPort);
else
mClientAddr.sin_port = (nPort);
return;
}

// Listening on a TCP Socket
S16
CTCPSocket::Listen ()
{
S32 iRet;
iRet = listen (mSockfd, MAXCONNECTIONS);
if (iRet != 0)
{
return FAILURE;
}
return SUCCESS;
}
// Waiting for a connection on a TCP Socket
SOCKET_FD CTCPSocket::Accept ()
{
S32 len;
SOCKET_FD Sockfd;
socklen_t temp_len;
struct sockaddr_in temp_self_addr;
memset (&temp_self_addr, 0, sizeof (temp_self_addr));
if ((getsockname (mSockfd, (sockaddr *) & temp_self_addr, &temp_len)) < 0)
{
perror (“Error in geting self address”);
}
else
{

}
len = sizeof (mAddr);
Sockfd = accept (mSockfd, (struct sockaddr *) &mAddr, (socklen_t *) & len);

if (Sockfd < 0)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
//print error
}
else if (errno == EBADF)
{
//print error
}
else if (errno == ECONNABORTED)
{
//print error
}
else if (errno == EFAULT)
{
//print error
}
else if (errno == EINTR)
{
//print error
}
else if (errno == EINVAL)
{
//print error
}
else if (errno == EMFILE)
{
//print error
} }
else if (errno == ENFILE)
{
//print error
}
else if (errno == ENOTSOCK)
{
//print error
}
else if (errno == EOPNOTSUPP)
{
//print error
}
else if (errno == ENOBUFS)
{
//print error
}
else if (errno == ENOMEM)
{
//print error
}
else if (errno == ENOSR)
{
//print error
}
else if (errno == EPROTO)
{
//print error
return Sockfd;
}
return Sockfd;
}
// Connect to TCP Server
S16 CTCPSocket::Connect (S8 * sHost, S32 nPort)
{
S32 iRet;
mAddr.sin_family = AF_INET;
mAddr.sin_port = htons (nPort);

iRet = inet_pton (AF_INET, sHost, &mAddr.sin_addr);
if (iRet != 1)
{
if (errno == EAFNOSUPPORT)
{
//print error
}
else
{
//print error
}
return FAILURE;
}

iRet = connect (mSockfd, (sockaddr *) & mAddr, sizeof (mAddr));

if (iRet != SUCCESS)
{
switch(errno)
{
case EADDRNOTAVAIL:

break;
case EAFNOSUPPORT:

break;
case EALREADY :

break;
case EBADF:
break;
case ECONNREFUSED:

break;
case EINPROGRESS:

break;
case EINTR:

break;
case EISCONN:

break;
case ENETUNREACH:

break;
case ENOTSOCK:

break;
case EPROTOTYPE:

break;
case ETIMEDOUT:
break;
case EIO:
break;
case ELOOP:

break;
case ENAMETOOLONG :
break;
case ENOENT:

break;
case ENOTDIR:

break;
case EACCES:

break;
case EADDRINUSE:

break;
case ECONNRESET :
break;
case EHOSTUNREACH:

break;
case EINVAL:
break;
case ENETDOWN:

break;
case ENOBUFS:

break;
case EOPNOTSUPP:

break;
default:

break;
}
}
else
{
}
return iRet;
}

//Get TCP Client socket fd
void CTCPClientSocket::GetClientSockFD ()
{
mClientFd = mSockfd;
}

// Send Data on TCP Connection
S32 CTCPSocket::Send (SOCKET_FD Sockfd, S8 * Str, S32 msg_len)
{
S32 iRet,bufferIndex,lengthSend;

bufferIndex = 0;
lengthSend = 0;

for(S32 i=0 ;i<MAX_RETRY && lengthSend!=msg_len;i++)
{
iRet = send (Sockfd, &Str[bufferIndex], msg_len-lengthSend, 0);
if (iRet <= 0)
{
if (errno == EPIPE)
{

}
return FAILURE;
}
lengthSend += iRet;
bufferIndex += iRet;
}
if(lengthSend!=msg_len)
{
return FAILURE;
}
return lengthSend;
}

// Receive Data on TCP Connection
S32 CTCPSocket::Receive (SOCKET_FD Sockfd, void *Str, S32 max_len)
{
U8 Buff[BUFFER_SIZE + 1];
S32 iRet,bufferIndex,lengthToRead;

memset (Buff, 0, sizeof (Buff));
bufferIndex = 0;
lengthToRead = max_len;
for(S32 i=0 ;i<MAX_RETRY && lengthToRead!=0;i++)
{
iRet = recv (Sockfd, &Buff[bufferIndex],lengthToRead, 0);
if (iRet <= 0)
{

switch(errno)
{
case EBADF:
break;
case ECONNRESET:
break;
case EFAULT:
break;
case EINTR:
break;
case EINVAL : break;
case ENOTSOCK: break;
case EOPNOTSUPP: break;
case ETIMEDOUT: break;
case EIO:
break;
case ENOBUFS:
break;
case ENOMEM:
break;
case ENOSR:
break;
case 2 :
break;
}
return FAILURE;
}
bufferIndex += iRet;
lengthToRead -= iRet;
}
return max_len-lengthToRead;
}

// Default UDP socket constructor
CUDPSocket::CUDPSocket ()
{
}

CUDPSocket::~CUDPSocket ()
{
}
//Send data over UDP socket
S32 CUDPSocket::SendTo (S8 * Str)
{
S32 iRet;
iRet = sendto (mSockfd, Str, strlen (Str), 0, (struct sockaddr *) &mClientAddr,sizeof (mClientAddr));

if (iRet != (S32) strlen (Str))
{
return FAILURE;
}
return iRet;
}
S32 CUDPSocket::SendTo (void *Buff, S32 Size)
{
S32 iRet;
iRet = sendto (mSockfd, Buff, Size, 0, (struct sockaddr *) &mClientAddr,sizeof (mClientAddr));

if (iRet != Size)
{
return FAILURE;
}
return iRet;
}

// Receive data over UDP socket
S32 CUDPSocket::ReceiveFrom (void *Buff)
{
S32 iRet, len;
S8 *host;
S32 nPort;

len = sizeof (mClientAddr);

iRet = recvfrom (mSockfd, Buff, BUFFER_SIZE, 0,(struct sockaddr *) &mClientAddr, (socklen_t *) & len);
if (iRet <= 0)
{
if (errno == EBADF)
{
}
else if (errno == ECONNRESET)
{
}
else if (errno == EFAULT)
{
}
else if (errno == EINTR)
{
}
else if (errno == EINVAL)
{
}
else if (errno == ENOTSOCK)
{
}
else if (errno == EOPNOTSUPP)
{

}
else if (errno == ETIMEDOUT)
{

}
else if (errno == EIO)
{

}
else if (errno == ENOBUFS)
{

}
else if (errno == ENOMEM)
{

}
else if (errno == ENOSR)
{

}

return FAILURE;
}

host = inet_ntoa (mClientAddr.sin_addr);
nPort = ntohs (mClientAddr.sin_port);

return iRet;
}
S32 CUDPSocket::ReceiveFrom (void *Buff, S8 * sHost, S32 * nPort)
{
S32 iRet, len;
S8 *host;

len = sizeof (mClientAddr);

iRet = recvfrom (mSockfd, Buff, BUFFER_SIZE, 0,
(struct sockaddr *) &mClientAddr, (socklen_t *) & len);
if (iRet <= 0)
{
if (errno == EBADF)
{

}
else if (errno == ECONNRESET)
{

}
else if (errno == EFAULT)
{
}
else if (errno == EINTR)
{

}
else if (errno == EINVAL)
{

}
else if (errno == ENOTSOCK)
{
}
else if (errno == EOPNOTSUPP)
{
//print errors
}
else if (errno == ETIMEDOUT)
{

}
else if (errno == EIO)
{

}
else if (errno == ENOBUFS)
{

}
else if (errno == ENOMEM)
{
}
else if (errno == ENOSR)
{

}

return FAILURE;
}

host = inet_ntoa (mClientAddr.sin_addr);
*nPort = ntohs (mClientAddr.sin_port);
strcpy (sHost, host);
return iRet;
}
CTCPServerSocket::CTCPServerSocket (S32 nPort)
{
if (CTCPSocket::Create () != SUCCESS)
{
}
if (CTCPSocket::Bind (nPort,NULL, true, true) != SUCCESS)
{

}
if (CTCPSocket::Listen () != SUCCESS)
{

}
mListenFd = mSockfd;

mListenFd, (int)nPort);

}
CTCPServerSocket::CTCPServerSocket ()
{
if (CTCPSocket::Create () != SUCCESS)
{
}
}
CTCPServerSocket::~CTCPServerSocket ()
{
mListenFd = -1;

}
CTCPClientSocket::CTCPClientSocket ()
{
if (CTCPSocket::Create () != SUCCESS)
{
}
else
{
mClientFd = mSockfd;
status = 0;
}
}
// Send data over TCP Socket connection
S32 CTCPClientSocket::Send (S8 * Str, S32 msg_len)
{
S32 iRet;

iRet = CTCPSocket::Send (mClientFd, Str, msg_len);
if (iRet != msg_len)
{
return FAILURE;
}
return iRet;
}

// UDP Server Socket class Constructor
CUDPServerSocket::CUDPServerSocket (S32 nPort,S8 *IP, bool loopback_flag)
{
if (CUDPSocket::Create () != SUCCESS)
{
return;
}
if (CSocket::Bind (nPort,IP, true, loopback_flag) != SUCCESS)
{
return;
}
mListenFd = mSockfd;
mListenFd, (int)nPort);

}
CUDPServerSocket::CUDPServerSocket ()
{
if (CUDPSocket::Create () != SUCCESS)
{
return;
}
mListenFd = mSockfd;

}
CUDPServerSocket::~CUDPServerSocket ()
{
}
CUDPClientSocket::CUDPClientSocket ()
{
if (CUDPSocket::Create () != SUCCESS)
{
}
else
{
mClientFd = mSockfd;
}
memset (&mClientAddr, 0, sizeof (struct sockaddr_in));
mClientAddr.sin_family = AF_INET;
}

//Socket.h
ClientAd
// TCP/UDP base Socket class
class CSocket
{

// Operations
public:
// Constructor —
CSocket() ;
// — Constructor
CSocket(S32 x){mSockfd=x;}

// Destructor —
~CSocket() ;
// — Destructor

// Overrides
public:

// Server Initialization —
// Bind Socket to a Port —
S16 Bind ( S32 nPort,S8* p_IP, bool htonsFlag, bool loopback_flag=true) ;
// — Bind Socket to a Port

// Set Socket to Non-Blocking —
S16 SetNonBlocking ( const S16 ) ;
// — Set Socket to Non-Blocking

// Close Socket —
void Close () ;
// — Close Socket

// Socket FD —
SOCKET_FD mSockfd;
// — Socket FD

int status; // status of connection

// Socket Address Structure —
struct sockaddr_in mAddr;
// — Socket Address Structure
} ;
// TCP Socket class
class CTCPSocket : public CSocket
{
public:
// Constructor —
CTCPSocket() ;
// Parameterized constructor
CTCPSocket(int x):CSocket(x){}

// Destructor —
virtual ~CTCPSocket() ;

// Overrides
public:
// Create Socket —
S16 Create () ;
// — Create Socket

// Server Initialization —
// Listen to a Socket Port —
S16 Listen () ;

// Accept Connection request from Client —
SOCKET_FD Accept () ;

// Client Initialization —
// Connect to Server —
S16 Connect ( S8* sHost, S32 nPort );

// Send Data to Socket —
S32 Send ( SOCKET_FD Sockfd, S8* Str, S32 msg_len) ;

// Receive Data from Socket —
S32 Receive (SOCKET_FD Sockfd, void* Str,S32 max_len=BUFFER_SIZE) ;
} ;

// UDP socket class
class CUDPSocket : public CSocket
{
// Attributes
public:

// Operations
public:
// Constructor —
CUDPSocket() ;

// Destructor —
virtual ~CUDPSocket() ;

// Overrides
public:

// Create Socket —
S16 Create () ;

// Send Data to Socket —
S32 SendTo ( S8* ) ;
S32 SendTo ( void* Buff, S32 Size) ;

// Receive Data from Socket —
S32 ReceiveFrom ( void* ) ;
S32 ReceiveFrom ( void* Buff, S8* sHost, S32 *nPort) ;

// Receive Data from Socket —
void SetHostnPort ( S8* host, S32 nPort, bool htonsFlag ) ;

// Attributes
protected:

// Attributes
public:
// Client Address structure —
sockaddr_in mClientAddr;

} ;

// TCP Server Socket class
class CTCPServerSocket : public CTCPSocket
{
// Attributes
public:
// Listen FD —
SOCKET_FD mListenFd;

// Operations
public:
// Constructor
CTCPServerSocket ( S32 nPort ) ;
CTCPServerSocket () ;

// Destructor —
virtual ~CTCPServerSocket() ;

// Overrides
public:

};

// TCP Client Socket class
class CTCPClientSocket : public CTCPSocket
{
// Attributes
public:
SOCKET_FD mClientFd;
// Operations
public:
// Constructor —
CTCPClientSocket ();
CTCPClientSocket(int x):CTCPSocket(x)
{mClientFd=x;}
CTCPClientSocket (S16 bFlag);

// Destructor –
~CTCPClientSocket(){};

// Overrides
public:
// Send Data to Socket —
S32 Send ( S8* Str,S32 msg_len);
// — Send Data to Socket

void GetClientSockFD();
};

// UDP Server Socket class
class CUDPServerSocket : public CUDPSocket
{
// Attributes
public:
// Listen FD —
SOCKET_FD mListenFd;

// Operations
public:
// Constructor
CUDPServerSocket ( S32 nPort ,S8 *IP,bool loopback=true) ;
CUDPServerSocket ();

// Destructor —
virtual ~CUDPServerSocket() ;

// Overrides
public:

};

// UDP Client Socket class
class CUDPClientSocket : public CUDPSocket
{
// Attributes
public:
SOCKET_FD mClientFd;

// Operations
public:
// Constructor —
CUDPClientSocket ();

// Destructor —
virtual ~CUDPClientSocket(){};

// Overrides
public:
};

public class InterfaceClient
{
private int m_port;
private string m_ip;
private UdpClient m_client;
private const int maxDataLength = 8192;

public InterfaceClient(int p_port, string p_ip, int p_receiveTimeOut)
{
m_port = p_port;
m_ip = p_ip;
m_client = new UdpClient(m_ip, m_port);
m_client.Client.ReceiveTimeout = p_receiveTimeOut;
}
public void sendRequest(string p_request)
{
byte[] l_dataToSend = new byte[maxDataLength];
l_dataToSend = Encoding.ASCII.GetBytes(p_request);
}
m_client.Send(l_dataToSend, l_dataToSend.Length);
}

public string receiveResponse()
{
IPEndPoint l_sender = new IPEndPoint(IPAddress.Any, 0);
byte[] l_dataToReceive = new byte[maxDataLength];
l_dataToReceive = m_client.Receive(ref l_sender);
return Encoding.ASCII.GetString(l_dataToReceive, 0, l_dataToReceive.Length);
}
}
public class ExternalInterfaceClient
{
private InterfaceClient m_client;
public ExternalInterfaceClient(string p_Ip, int p_port, int p_receiveTimeOut)
{
m_client = new InterfaceClient(p_port, p_Ip, p_receiveTimeOut);
}

private <return_type> getRoutes( )
{

try
{
//construct XML query
string l_query = “”;
//send query
m_client.sendRequest(l_query);
string l_response = m_client.receiveResponse();
//parse response
l_result = l_outputSerializer.Deserialize(l_response);
}
catch (Exception e)
{
return null;
}
return l_result;
}

}

C# code:

public Client(int port, string ip, int timeOut)
{
m_port = port;
m_ip = ip;
m_client = new UdpClient(m_ip, m_port);
m_client.Client.timeout = timeOut;
}

m_client = new Client(port_num, ip, timeOut)

string response=m_client.sendRequest(x_query); // here x_query is the xml query which has to be handled by backend

Leave a Reply

Your email address will not be published. Required fields are marked *