도그소프트
[C++]소켓 프로그래밍(Server,Client) 본문
- Server -
//server
#pragma comment(lib,"ws2_32.lib")
#include <WinSock2.h>
#include <iostream>
int main() {
//Winsock startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if (WSAStartup(DllVersion, &wsaData) != 0)
//If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup
{
MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
exit(1);
}
SOCKADDR_IN addr; //Address that we will bind our listening socket to
int addrlen = sizeof(addr); //length of the address (required for accept call)
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(1111);//port
addr.sin_family = AF_INET;//IPv4 Socket
SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
//Create socket to listen for new connections
bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
//Bind the address to the socket
listen(sListen, SOMAXCONN);
//Places sListen socket int a state in which it is listening for an incoming connection.
//Note:SOMAXCONN = Socket Oustanding Max connections
SOCKET newConnection; //Socket to hold the client's connection
newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); //Accept a new connection
if (newConnection == 0) { //If accepting the client connection failed
std::cout << "Failed to accept the client's connection." << std::endl;
}
else {//If client connection properly accepted
std::cout << "Client Connected!" << std::endl;
char MOTD[256] = "Welcome! This is the Message of the Day.";//Create buffer with message of the day
send(newConnection, MOTD, sizeof(MOTD), NULL);//Send MORD buffer
}
system("pause");
return 0;
}
- client -
//client
#pragma comment(lib,"ws2_32.lib")
#include <WinSock2.h>
#include <iostream>
int main() {
//Winsock startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if (WSAStartup(DllVersion, &wsaData) != 0)
//If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup
{
MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
exit(1);
}
SOCKADDR_IN addr; //Address to be binded to our Connection socket
int sizeofaddr = sizeof(addr); //Need sizeofaddr for the connect function
addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //Address=localhost(this pc)
addr.sin_port = htons(1111);//port //Port=1111
addr.sin_family = AF_INET;//IPv4 Socket //IPv4 Socket
SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL);//Set Connection socket
if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0){//If we are unable to connect
MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
return 0;//Failed to Connect
}
else {//If we are able to connect
std::cout << "Connected!" << std::endl;
}
char MOTD[256];
recv(Connection, MOTD, sizeof(MOTD), NULL);//Receive Message of the Day buffer into MOTD array
std::cout << "MOTD:" << MOTD << std::endl;
system("pause");
return 0;
}
}
system("pause");
return 0;
}