void MasterNodeConnection::shutdown() { auto self = shared_from_this(); std::lock_guard<ioMutexType> lock(mutex); if (disposed) return; BOOST_LOG_SEV(log, LogLevel::Info) << "Shutting down."; auto h = handler.lock(); if (h != nullptr) h->connectionShutdown(); try { tcpSocket().shutdown(socketType::shutdown_both); } catch(...) { } try { tcpSocket().cancel(); } catch (...) { } if (h != nullptr) h->connectionShutdownDone(); if (accepted) { _master.removeNodeConnection(iter); accepted = false; } disposed = true; }
int Socket::init() { struct sockaddr_in servaddr; int optval = 1; sockfd = tcpSocket(AF_INET, SOCK_STREAM, 0); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); // Eliminates "Address already in use" error from bind if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)) < 0) Error::sys("setsockopt"); if (socktype == SRV_SOCKET){ servaddr.sin_addr.s_addr = htonl(INADDR_ANY); tcpBind(sockfd, (SA *) &servaddr, sizeof(servaddr)); tcpListen(sockfd, LISTENQ); } else if (socktype == CLI_SOCKET){ if (inet_pton(AF_INET, host, &servaddr.sin_addr) < 0) Error::quit("inet_pton error for %s", host); tcpConnect(sockfd, (SA *)&servaddr, sizeof(servaddr)); } else { Error::quit("Unkown SockType"); } /* For client, this sockfd is connfd, * for server, this sockfd is listenfd. */ return sockfd; }
/* -- FUNCTION: createTransferSocket -- -- DATE: September 29, 2011 -- -- REVISIONS: (Date and Description) -- -- DESIGNER: Luke Queenan -- -- PROGRAMMER: Luke Queenan -- -- INTERFACE: void createTransferSocket(int *socket); -- -- RETURNS: void -- -- NOTES: -- This function creates a transfer socket for the server to communicate with -- the client. The socket is bound to port 7000. */ void createTransferSocket(int *socket) { int *defaultPort = (int*)malloc(sizeof(int)); *defaultPort = TRANSFER_PORT; // Create a TCP socket if ((*socket = tcpSocket()) == -1) { systemFatal("Cannot Create Socket!"); } // Allow the socket to be reused immediately after exit if (setReuse(socket) == -1) { systemFatal("Cannot Set Socket To Reuse"); } // Bind an address to the socket if (bindAddress(defaultPort, socket) == -1) { systemFatal("Cannot Bind Address To Socket"); } free(defaultPort); }
/* -- FUNCTION: initializeServer -- -- DATE: September 23, 2011 -- -- REVISIONS: -- -- DESIGNER: Karl Castillo -- -- PROGRAMMER: Karl Castillo -- -- INTERFACE: void initalizeServer(int* port, int* socket) -- port - the port the client will listen on -- socket - the socket that will hold the new socket -- -- RETURNS: void -- -- NOTES: -- This function will create the socket, set reuse and listen for any incoming -- connections from the server. */ void initalizeServer(int* port, int* socket) { int sock = 0; // Create a TCP socket if ((sock = tcpSocket()) == -1) { systemFatal("Cannot Create Socket!"); } // Allow the socket to be reused immediately after exit if (setReuse(&sock) == -1) { systemFatal("Cannot Set Socket To Reuse"); } // Bind an address to the socket if (bindAddress(port, &sock) == -1) { systemFatal("Cannot Bind Address To Socket"); } // Set the socket to listen for connections if (setListen(&sock) == -1) { systemFatal("Cannot Listen On Socket"); } if((*socket = acceptConnection(&sock)) == -1) { systemFatal("Cannot Accept on Socket"); } close(sock); }
void get_available_address_v4(io_service& ios,std::set<address>& addrs) { addrs.clear(); error_code ec; std::vector<ip_interface> interfaces=enum_net_interfaces(ios,ec); address realBindAddr; for(std::size_t i=0;i<interfaces.size();++i) { if(is_loopback(interfaces[i].interface_address) ||is_any(interfaces[i].interface_address) ||interfaces[i].interface_address.is_v6() ) { continue; } //test can we bind this port endpoint edp(interfaces[i].interface_address,0); boost::asio::ip::tcp::socket tcpSocket(ios); tcpSocket.open(boost::asio::ip::tcp::v4(),ec); tcpSocket.bind(edp,ec); if (!ec&&!is_any(realBindAddr=tcpSocket.local_endpoint(ec).address())) { addrs.insert(realBindAddr); } else { addrs.erase(realBindAddr); } tcpSocket.close(ec); } }
/* -- FUNCTION: initializeServer -- -- DATE: March 12, 2011 -- -- REVISIONS: September 22, 2011 - Added some extra comments about failure and -- a function call to set the socket into non blocking mode. -- -- DESIGNER: Luke Queenan -- -- PROGRAMMER: Luke Queenan -- -- INTERFACE: void initializeServer(int *listenSocket, int *port); -- -- RETURNS: void -- -- NOTES: -- This function sets up the required server connections, such as creating a -- socket, setting the socket to reuse mode, binding it to an address, and -- setting it to listen. If an error occurs, the function calls "systemFatal" -- with an error message. */ void initializeServer(int *listenSocket, int *port) { // Create a TCP socket if ((*listenSocket = tcpSocket()) == -1) { systemFatal("Cannot Create Socket!"); } // Allow the socket to be reused immediately after exit if (setReuse(&(*listenSocket)) == -1) { systemFatal("Cannot Set Socket To Reuse"); } // Bind an address to the socket if (bindAddress(&(*port), &(*listenSocket)) == -1) { systemFatal("Cannot Bind Address To Socket"); } // Set the socket to listen for connections if (setListen(&(*listenSocket)) == -1) { systemFatal("Cannot Listen On Socket"); } }
void monitor() { sfd = tcpSocket(); if (!sfd) die(1,"Could not allocate socket"); if (reuseSocket(sfd)) die(2,"Failed to reuse socket %d",sfd); if (bindSocket(sfd, address, htons(port))) die(3,"Failed to bind to %d.%d.%d.%d:%d",IP(address),port); if (listen(sfd,backlog)) die(4,"Failed to listen on port %d",port); if (nonblock(sfd)<0) die(5,"Failed to set nonblocking on socket %d", sfd); debug("Listening on %d.%d.%d.%d:%d",IP(address),port); }
void LwipNetInterface::tcpConnect(int* sockfd, const char* ip, word16 port, int udp) { SOCKADDR_IN_T addr; build_addr(&addr, ip, port, udp); tcpSocket(sockfd, udp); if (!udp) { if (connect(*sockfd, (const struct sockaddr* )&addr, sizeof(addr)) != 0) { LWIP_ASSERT("tcp connect failed",0); } } }
void ClientController::onTimer_Timer(int id) { if(id == TIMERID_RECONNECT) { // TODO : retry max check.. retryConnectCnt_++; try { tcpSocket()->connect(); timerObj_->killTimer(id); } catch(...) { // retry! } return; } BaseController::onTimer_Timer(id); }
int main(int argc, char *argv[]) { int sctcp; char hostname[80] = ""; struct sockaddr_in SC_link = { 0 }; int server_port=8000; int childPid=0; static LList userlist; InitList(&userlist); pthread_t id; int ret; printf("Server is starting\n"); sctcp=tcpSocket(); //client-server comunicate with tcp Setsockopt(sctcp); //set SO_REUSEADDR,SO_LINGER opt GetHostName(hostname, sizeof(hostname)); CreateSockAddr(hostname,&SC_link,server_port); Bind(sctcp, (struct sockaddr *) &SC_link,sizeof(SC_link)); Listen(sctcp); printf("Server started successfully and it is ready now\n"); printf("Now entered listening mode\n"); for (;;) { struct sockaddr_in client_sockaddr = { 0 }; int cli_socket, cli_sock2,clientLength = sizeof(client_sockaddr); (void) memset(&client_sockaddr, 0, sizeof(client_sockaddr)); cli_socket = Accept(sctcp,(struct sockaddr *) &client_sockaddr, &clientLength); if (-1 == cli_socket) { perror("accept()"); } threadargs newargs; newargs.sock=cli_socket; newargs.list=&userlist; // accept_cli(&newargs); ret=pthread_create(&id,NULL,(void *)accept_cli,&newargs); if(ret!=0) perror("thread create error"); } return EXIT_SUCCESS; }
void MasterNodeConnection::didAccept() { auto self = shared_from_this(); std::lock_guard<ioMutexType> lock(mutex); accepted = true; log.setChannel(str(format("Unknown [%s]") % tcpSocket().remote_endpoint())); auto headerBuffer = std::make_shared<std::uint32_t>(); readAsync(asio::buffer(headerBuffer.get(), 4), [this, headerBuffer] (const boost::system::error_code& error, std::size_t readCount){ try { if (error) { MSCThrow(boost::system::system_error(error)); } std::uint32_t header = *headerBuffer; std::shared_ptr<MasterNodeConnectionHandler> h; if (header == ControlStreamHeaderMagic) { h = std::make_shared<MasterNode>(shared_from_this()); } else if (header == VersionDownloadRequestMagic) { MSCThrow(NotImplementedException()); } else if (header == DataStreamMagic) { h = std::make_shared<MasterNodeClientStream>(shared_from_this()); } else { MSCThrow(InvalidOperationException( str(format("Invalid header magic 0x%08x received.") % header))); } assert(h != nullptr); handler = h; h->service(); } catch (...) { performShutdownByError(boost::current_exception_diagnostic_information()); } }); }
/* -- FUNCTION: initConnection -- -- DATE: September 23, 2011 -- -- REVISIONS: -- -- DESIGNER: Karl Castillo -- -- PROGRAMMER: Karl Castillo -- -- INTERFACE: int initConnection(int port, const char* ip) -- port - the port the client will connect to to the server -- ip - ip address of the server -- -- RETURNS: int - the new socket created -- -- NOTES: -- This function will create the socket, set reuse and connect to the server. */ int initConnection(int port, const char* ip) { int socket; // Creating Socket if((socket = tcpSocket()) == -1) { systemFatal("Error Creating Socket"); } // Setting Socket to Reuse if(setReuse(&socket) == -1) { systemFatal("Error Set Socket Reuse"); } // Connect to transfer server if(connectToServer(&port, &socket, ip) == -1) { systemFatal("Cannot Connect to server"); } return socket; }
int TCPClient::connect ( const char * ip, const char * port ) { int rv; char s[INET6_ADDRSTRLEN]; addrinfo hints, *servinfo, *p; try { memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo( ip, port, &hints, &servinfo)) != 0) { throw "getaddrinfo: " + std::string ( gai_strerror(rv) ); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if (tcpSocket(p->ai_family, p->ai_protocol) == -1) { continue; } if (::connect(socketDesc, p->ai_addr, p->ai_addrlen) == -1) { continue; } break; } if (p == NULL) { throw "failed to connect"; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); freeaddrinfo(servinfo); // all done with this structure } catch ( LogString e ) { } return 0; }
main() { WSADATA wsaData; // Stores Winsock library information struct timeval timeout; // The timeout value for the select system call char sTicker[10]; // A local variable to hold the user-inputted ticker. fd_set fdset; // Set of "watched" file descriptors // The select system call is set to timeout after 10 seconds with no data existing // on the socket. timeout.tv_sec = 10; timeout.tv_usec = 0; // The Winsock library in initialized. if (WSAStartup(0x101, &wsaData) != 0) { cout << "Error initializing WinSock library: " << WSAGetLastError() << endl; return 0; } try { // A TCP socket is created using the port number defined in PORT_NUM2 as // the position communication port. XPCTcpSocket tcpSocket((long int)PORT_NUM2); // The client connects to the specified UNIX server using the socket port // specified in the constructor. tcpSocket.vConnect(UNIX_SERVER); // Loop forever until the user requests to exit. while(1) { XPCPosition newPosition; // A new instance of the // XPCPosition is created. // Request the ticker from the user. cout << "Enter Ticker Symbol: " << flush; cin >> sTicker; // If the user enters the "QUIT" command, the loop breaks, and the // client exits. if (strcmp(sTicker, "QUIT") == 0) break; // The ticker is stored in the XPCPosition instance. newPosition.vSetTicker(sTicker); // The instance of XPCPosition is sent to the server tcpSocket.iSendMessage((void *)&newPosition, sizeof(newPosition)); // The socket file descriptor set is cleared and the socket file // descriptor contained within tcpSocket is added to the file // descriptor set. FD_ZERO(&fdset); FD_SET(tcpSocket.iGetSocketFd(), &fdset); // A select is setup to return when data is available on the socket // for reading. If data is not available after 10 seconds, select // returns with a value of 0. If data is available on the socket, // the select returns and data can be retrieved off the socket. int iSelectRet = select(tcpSocket.iGetSocketFd() + 1, &fdset, NULL, NULL, &timeout); // If select returns a -1, then it failed and the client exits. if (iSelectRet == -1) { cout << "Select failed: " << WSAGetLastError() << endl; return 0; } // If the select returns a 0, then the select timeout. else if (iSelectRet == 0) { cout << "Select timed out: Server Not Responding" << endl; continue; } // If data is available on the TCP socket, the data is retrieved // and placed in the instance of XPCPosition. The new position // is displayed for the user. if (FD_ISSET(tcpSocket.iGetSocketFd(), &fdset) != 0) { tcpSocket.iRecieveMessage((void *)&newPosition, sizeof(newPosition)); cout << "Ticker: " << newPosition.sGetTicker() << " Position: " << newPosition.iGetPosition() << endl; } } } // Socket related exceptions are caught and displayed. catch(XPCException &exceptObject) { cout << exceptObject.sGetException() << endl; } // The client releases Winsock resources when exiting. if (WSACleanup() != 0) { cout << "Error cleaning up WinSock library: " << WSAGetLastError() << endl; } }
main() { // Local variables used to hold user-inputted components of a XPCTransaction // instance. char sUser[50]; // User name char sTicker[10]; // Ticker symbol char cBS; // Buy/Sell indicator long int iAmount; // Number of shares bought or sold // Before using sockets on the Windows-NT operating system, the Winsock library // must be initialized. WSADATA wsaData; if (WSAStartup(0x101, &wsaData) != 0) { cout << "Error initializing WinSock library: " << WSAGetLastError() << endl; return 0; } // The name of the user is retrieved from the console and is stored in the local // sUser variable. cout << "Enter your User Name: " << flush; cin >> sUser; try { // An instance of the XPCTcpSocket is created. At this point a TCP // socket has been created and a port has been defined. XPCTcpSocket tcpSocket((long int)WINDOWS_NT_PORT_NUM); // Connect to the server. tcpSocket.vConnect(UNIX_SERVER); // Loop forever prompting the user for transaction record data. while(1) { cout << "Enter Ticker Symbol: " << flush; cin >> sTicker; // If the user enters "QUIT", exit the loop. if (strcmp(sTicker, "QUIT") == 0) break; cout << "Enter Buy(B) or Sell(S): " << flush; cin >> cBS; cout << "Enter Quantity: " << flush; cin >> iAmount; // Create a transaction record class instance XPCTransaction newTransaction(sUser, sTicker, cBS, iAmount); // Send the transaction record to the UNIX server using the client // version of iSendMessage. tcpSocket.iSendMessage((void *)&newTransaction, sizeof(newTransaction)); // Suspend process execution until the UNIX server replies with the // updated position. The client version of the iReceiveMessage // method is used. tcpSocket.iRecieveMessage((void *)&newTransaction, sizeof(newTransaction), MSG_WAITALL); // Display the newly updated position cout << "Ticker: " << newTransaction.sGetTicker() << " New Position: " << newTransaction.iGetAmount() << endl; } } catch(XPCException &exceptObject) { cout << exceptObject.sGetException() << endl; } // Disconnect from the Windows NT socket library. The socket is already closed // since the instance of XPCUdpSocket got destructed after it left the // try-catch block. WSACleanup(); }
int main() { XPCUserPosition userPositions[50]; // Initialize an array of 50 user positions. XPCStockPosition *individualPosition; // A pointer to an individual ticker // position. int iNumUsers = 0; // The number of user positions. XPCTransaction newTransaction; // An instance of a stock transaction // record. int iFound; // A flag indicating whether or not a // user position is found. XPCTcpSocket *clientConnection; // Connection dedicated for client communication char sHost[80]; // Connected host try { // An instance of XPCTcpSocket is created. A TCP socket is created. XPCTcpSocket tcpSocket((long int)UNIX_PORT_NUM); tcpSocket.vBindSocket(); tcpSocket.vListen(); // Accepts a client connection. Processing is suspended until the // client connects clientConnection = tcpSocket.Accept(sHost); cout << "A client from " << sHost << " connected" << endl; // Loop forever receiving transaction messages from Windows NT clients. while(1) { // The client's message is recieved int iNumBytes = clientConnection->iRecieveMessage((void *)&newTransaction, sizeof(newTransaction), MSG_WAITALL); #ifdef WINDOWS_NT if (WSAGetLastError() == WSAECONNRESET) #else if ((iNumBytes == 0) || (errno == ECONNRESET)) #endif { // The client has disconnected. Delete the connection and // suspend processing until a new client connects delete clientConnection; clientConnection = tcpSocket.Accept(sHost); cout << "A client from " << sHost << " connected" << endl; // Wait for a message clientConnection->iRecieveMessage((void *)&newTransaction, sizeof(newTransaction), MSG_WAITALL); } // Display the components of the transaction received. cout << "Got New Transaction:" << endl; cout << "User: "******"Ticker: " << newTransaction.sGetTicker() << endl; cout << "BS: " << newTransaction.cGetBS() << endl; cout << "Amount: " << newTransaction.iGetAmount() << endl; // Set the user-position found flag to false. iFound = 0; // Loop through all user positions and locate a position matching // the user contained within the transaction record received. for (int iUserCount = 0; iUserCount < iNumUsers; iUserCount++) { // If a position exists for the user, locate the position // for the ticker contained within the transaction record. if (strcmp(userPositions[iUserCount].sGetUser(), newTransaction.sGetUser()) == 0) { // If a ticker position exists add the transaction // amount to the current position. if ((individualPosition = userPositions[iUserCount].FindPosition(newTransaction.sGetTicker())) != NULL) { individualPosition->vAddPosition(newTransaction.iGetAmount(), newTransaction.cGetBS()); } // If a position does not exists for the given // ticker, add a new ticker position to the user's // portfolio. else { individualPosition = userPositions[iUserCount].AddNewPosition(newTransaction.sGetTicker(), newTransaction.iGetAmount(), newTransaction.cGetBS()); } // Set the user position found flag to true. iFound = 1; break; } } // If the user position found flag is false add a new user // position. if (iFound == 0) { // If the number of user positions is currently 50, no more // user positions can be added. Set the individual user // position to NULL. if (iNumUsers == 50) individualPosition = NULL; else { // Add a new user position. userPositions[iNumUsers].vSetUser(newTransaction.sGetUser()); individualPosition = userPositions[iNumUsers].AddNewPosition(newTransaction.sGetTicker(), newTransaction.iGetAmount(), newTransaction.cGetBS()); // Increment the number of user positions by 1. iNumUsers++; } } // Display the new position, set the transaction record to reflect // the new position, and send the transaction record to the // appropriate client. cout << "New Position: " << individualPosition->iGetPosition() << endl; newTransaction.vSetAmount(individualPosition->iGetPosition()); // Uses iSendMessage to send the updated position to the connected // client clientConnection->iSendMessage((void *)&newTransaction, sizeof(newTransaction)); } } // Catch any exceptions that are caused by the TCP socket related classes. catch(XPCException &exceptObject) { cout << exceptObject.sGetException() << endl; return 0; } }
int main(int argc,char** argv) { boost::asio::io_service io; if(0) { boost::asio::ip::tcp::socket tcpSocket(io); { std::cout << "---------------------------------------------------------------------------------------" << std::endl; CAsioClient client(tcpSocket); boost::system::error_code ec; boost::progress_timer t; bool ret = client.Connect("127.0.0.1",8899,boost::posix_time::seconds(20),ec); if(ec) { std::cout << "---- Á¬½Óʧ°Ü" << ec.message() <<std::endl; } if(!ret) { std::cout << "---- Á¬½Óʧ°Ü" << ec.message() <<std::endl; } } CAsioClient client(tcpSocket); boost::system::error_code ec; char buf[1]; buf[0] = 'A'; { boost::progress_timer t; ec = client.Send(boost::asio::buffer(buf,1),boost::posix_time::seconds(20)); if(ec) { std::cout << "---- ·¢ËÍʧ°Ü" << ec.message() <<std::endl; } } std::vector<char> vec; vec.resize(10); { boost::progress_timer t; ec = client.Receive(boost::asio::buffer(vec),boost::posix_time::seconds(10)); if(ec) { //std::cout << vec.size() << std::endl; std::cout << "---- ½ÓÊÕʧ°Ü" << ec.message() <<std::endl; } } ec = client.Receive(boost::asio::buffer(vec),boost::posix_time::seconds(10)); if(ec) { //std::cout << vec.size() << std::endl; std::cout << "---- ½ÓÊÕʧ°Ü" << ec.message() <<std::endl; } }else { std::cout << "---------------------------------------------------------------------------------------" << std::endl; CAsioClient client; boost::system::error_code ec; bool ret = client.Connect("127.0.0.1",8899,boost::posix_time::seconds(20),ec); if(ec) { std::cout << "---- Á¬½Óʧ°Ü" << ec.message() <<std::endl; } if(!ret) { std::cout << "---- Á¬½Óʧ°Ü" << ec.message() <<std::endl; } char buf[1]; buf[0] = 'A'; ec = client.Send(boost::asio::buffer(buf,1),boost::posix_time::seconds(20)); if(ec) { std::cout << "---- ·¢ËÍʧ°Ü" << ec.message() <<std::endl; } std::vector<char> vec; vec.resize(10); { boost::progress_timer t; ec = client.Receive(boost::asio::buffer(vec),boost::posix_time::seconds(10)); if(ec) { //std::cout << vec.size() << std::endl; std::cout << "---- ½ÓÊÕʧ°Ü" << ec.message() <<std::endl; } } ec = client.Receive(boost::asio::buffer(vec),boost::posix_time::seconds(10)); if(ec) { //std::cout << vec.size() << std::endl; std::cout << "---- ½ÓÊÕʧ°Ü" << ec.message() <<std::endl; } } return 0; }