C++代码
- //Filename: TcpServerClass.cpp
- #include "TcpServerClass.hpp"
- TcpServer::TcpServer(int listen_port)
- {
- if ( (listenSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ) {
- throw "socket() failed";
- }
- memset(&servAddr, 0, sizeof(servAddr));
- servAddr.sin_family = AF_INET;
- servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- servAddr.sin_port = htons(listen_port);
- if ( bind(listenSock, (sockaddr*)&servAddr, sizeof(servAddr)) < 0 ) {
- throw "bind() failed";
- }
- if ( listen(listenSock, 10) < 0 ) {
- throw "listen() failed";
- }
- }
- bool TcpServer::isAccept()
- {
- unsigned int clntAddrLen = sizeof(clntAddr);
- if ( (communicationSock = accept(listenSock, (sockaddr*)&clntAddr, &clntAddrLen)) < 0 ) {
- return false;
- } else {
- std::cout << "Client(IP: " << inet_ntoa(clntAddr.sin_addr) << ") connected.\n";
- return true;
- }
- }
- void TcpServer::handleEcho()
- {
- const int BUFFERSIZE = 32;
- char buffer[BUFFERSIZE];
- int recvMsgSize;
- bool goon = true;
- while ( goon == true ) {
- if ( (recvMsgSize = recv(communicationSock, buffer, BUFFERSIZE, 0)) < 0 ) {
- throw "recv() failed";
- } else if ( recvMsgSize == 0 ) {
- goon = false;
- } else {
- if ( send(communicationSock, buffer, recvMsgSize, 0) != recvMsgSize ) {
- throw "send() failed";
- }
- }
- }
- close(communicationSock);
- }
C++代码
- //Filename: TcpServerClass.hpp
- #ifndef TCPSERVERCLASS_HPP_INCLUDED
- #define TCPSERVERCLASS_HPP_INCLUDED
- #include <unistd.h>
- #include <iostream>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- class TcpServer
- {
- private:
- int listenSock;
- int communicationSock;
- sockaddr_in servAddr;
- sockaddr_in clntAddr;
- public:
- TcpServer(int listen_port);
- bool isAccept();
- void handleEcho();
- };
- #endif // TCPSERVERCLASS_HPP_INCLUDED
演示程序:
C++代码
- //Filename: main.cpp
- //Tcp Server C++ style, single work
- #include <iostream>
- #include "TcpServerClass.hpp"
- int echo_server(int argc, char* argv[]);
- int main(int argc, char* argv[])
- {
- int mainRtn = 0;
- try {
- mainRtn = echo_server(argc, argv);
- }
- catch ( const char* s ) {
- perror(s);
- exit(EXIT_FAILURE);
- }
- return mainRtn;
- }
- int echo_server(int argc, char* argv[])
- {
- int port;
- if ( argc == 2 ) {
- port = atoi(argv[1]);
- } else {
- port = 5000;
- }
- TcpServer myServ(port);
- while ( true ) {
- if ( myServ.isAccept() == true ) {
- myServ.handleEcho();
- }
- }
- return 0;
- }
除非特别注明,鸡啄米文章均为原创
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。