/* * Network.h */
#include <iostream> #include <unistd.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h>
using namespace std;
#ifndef SERVER_H_ #define SERVER_H_
// 0. class INetwork{ virtual void listenSingleSocket() = 0; };
// 1. 서버사이드(Server-Side) class Server : public INetwork{
protected:
private: int welcomeSocket, newSocket;
public: Server(){ this->welcomeSocket = 0; this->newSocket = 0; }
void listenSingleSocket(){
char buffer[1024]; struct sockaddr_in serverAddr; struct sockaddr_storage serverStorage; socklen_t addr_size;
welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);
serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8000); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int i = 0;
while(i < sizeof(serverAddr.sin_zero) ){ serverAddr.sin_zero[i] = '\0'; i++; }
bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr) );
if ( listen(welcomeSocket, 5) == 0 ){ cout << "Listening\n"; } else { cout << "Error\n"; }
addr_size = sizeof(serverStorage); newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);
buffer[0] = 'H'; buffer[1] = 'e'; buffer[2] = 'l'; buffer[3] = 'l'; buffer[4] = 'o';
send(newSocket, buffer, 13, 0);
}
};
class Client : public INetwork{
private: int clientSocket; char buffer[1024]; struct sockaddr_in serverAddr; socklen_t addr_size;
public: Client(){ this->clientSocket = 0; }
void listenSingleSocket(){
clientSocket = socket(PF_INET, SOCK_STREAM, 0);
serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8000);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int i = 0; while (i < sizeof(serverAddr.sin_zero)){ serverAddr.sin_zero[i] = '\0'; i++; }
addr_size = sizeof(serverAddr);
connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);
// 문자열 전달 받음 - (unsigned) char[1024] recv(clientSocket, buffer, 1024, 0); cout << "데이터 전송 받은 문자:" << buffer << endl; }
};
#endif /* SERVER_H_ */
|