1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <WinSock2.h>
using namespace std;
 
#pragma comment(lib,"ws2_32.LIB")
 
struct temp {
    int age;
    char buf[10];
};
 
void Exception(const char* msg) {
    cout << msg << endl;
    LPVOID lpOSMsg;
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, WSAGetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPSTR)&lpOSMsg, 0NULL);
    cout << "[" << (char*)lpOSMsg << "]" << endl;
    LocalFree(lpOSMsg);
}
 
DWORD WINAPI RecvData(LPVOID pParam) {
    SOCKET sock = (SOCKET)pParam;
    char buf[1000]; 
 
    //ULONG isNonBlocking = 1;
    //ioctlsocket(sock,        //Non-Blocking으로 변경할 소켓
    //    FIONBIO,       //변경할 소켓의 입출력 모드
    //    &isNonBlocking //넘기는 인자, 여기서는 nonblocking설정 값
    //);
 
    while (true) {
        memset(buf, '\0'1000);
        
        int len = recv(sock, buf, 10000);
        if (WSAGetLastError() == WSAEWOULDBLOCK) {
        //    Sleep(2000);
        }
 
        if (len > 0) {
            cout << buf << endl;
        }
 
    }
 
}
 
int main() {
    WSADATA wsaData;
 
    BYTE nMajor = 2, nMinor = 2;
 
    WORD wVersionRequested = MAKEWORD(nMinor, nMajor);
    
    if (WSAStartup(wVersionRequested, &wsaData) == SOCKET_ERROR) {
        cout << "socket Initialize failed " << endl;
        return -1;
    }
    if (LOBYTE(wsaData.wVersion) != nMajor || HIBYTE(wsaData.wVersion) != nMinor) {
        cout << "socket version not equal" << endl;
        WSACleanup();
        return -1;
    }
 
    char ServerIP[50= { '\0' };
    SOCKET sock =  socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if (sock == INVALID_SOCKET)
        Exception("Do not make Socket");
 
    cin >> ServerIP;
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9000);
    addr.sin_addr.s_addr = inet_addr(ServerIP);
 
    if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR)
        Exception("Socket Error");
    
    HANDLE hThread = CreateThread(NULL0, RecvData, (LPVOID)sock, 0NULL);
 
 
    WSABUF wsaBuf;
    memset(&wsaBuf, 0sizeof(WSABUF));
    char buf[200];
 
    
    while (true) {
        memset(buf, '\0'200);
        cout << "Chat : ";
    
        cin >> buf;
 
        send(sock, buf, sizeof(buf), 0);
    
}
    return 0;
}
cs


+ Recent posts