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 103 104 105 106
| #include <Windows.h> #include <stdio.h> #include <iostream> #include <WinSock2.h> #include <WS2tcpip.h> #pragma comment(lib,"Ws2_32.lib")
#define BUF_SIZE 1024 char szMsg[BUF_SIZE];
unsigned SendMsg(void *arg) { SOCKET sock = *((SOCKET *)arg);
while (1) { scanf("%s", szMsg); if (!strcmp(szMsg, "QUIT\n") || !strcmp(szMsg, "quit\n")) { closesocket(sock); exit(0); }
send(sock, szMsg, strlen(szMsg), 0); }
return 0; }
unsigned RecvMsg(void* arg) { SOCKET sock = *((SOCKET*)arg);
char msg[BUF_SIZE]; while (1) { int len = recv(sock, msg, sizeof(msg) - 1, 0); if (len == -1) { return -1; } msg[len] = '\0'; printf("%s\n", msg); }
return 0; }
int main() { WORD wVersionRequested; WSADATA wsaData; int err;
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return -1; }
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); return -1; }
SOCKET hSock; hSock = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN servAdr; memset(&servAdr, 0, sizeof(SOCKADDR_IN)); servAdr.sin_family = AF_INET; servAdr.sin_port = htons(9999); inet_pton(AF_INET, "47.115.204.216", &servAdr.sin_addr);
if (connect(hSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR) { printf("connect error: %d\n", GetLastError()); return -1; } else { printf("欢迎来到聊天室,请输入您的用户名: "); }
HANDLE hSendHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)SendMsg, (void *)&hSock, 0, NULL);
HANDLE hReceiveHand = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)RecvMsg, (void*)&hSock, 0, NULL);
WaitForSingleObject(hSendHandle, INFINITE); WaitForSingleObject(hReceiveHand, INFINITE);
closesocket(hSock); WSACleanup(); }
|