当前位置:网站首页>C language QQ chat room small project [complete source code]
C language QQ chat room small project [complete source code]
2022-07-05 10:27:00 【Chenziqing: see】
Chat items are used to practice Windows Under the tcp socket Programming and thread synchronization , among send and recv Use , Yes tcp Chinese garbled code often encountered in data transmission 、 Problems such as incomplete data can be demonstrated and corrected .
Project renderings

Client code
#include <WinSock2.h> #include <iostream> #include <windows.h> #include <process.h> #include<WS2tcpip.h> #pragma comment(lib, "ws2_32.lib") #define NAME_SIZE 32 #define BUF_SIZE 256 char szName[NAME_SIZE] = "[DEFAULT]"; char szMsg[BUF_SIZE]; // Send a message to the server unsigned WINAPI SendMsg(void* arg) { //1 Receive the parameters passed in SOCKET hClntSock = *((SOCKET*)arg); char szNameMsg[NAME_SIZE + BUF_SIZE]; // Another name , News again // Cycle to receive messages from the console while (1) { fgets(szMsg, BUF_SIZE, stdin); // Blocked in this sentence // Exit mechanism When I received q or Q sign out if (!strcmp(szMsg, "Q\n") || !strcmp(szMsg, "q\n")) { closesocket(hClntSock); exit(0); } sprintf(szNameMsg, "%s %s", szName, szMsg);// String splicing send(hClntSock, szNameMsg, strlen(szNameMsg), 0);// send out } return 0; } // Receiving messages from the server unsigned WINAPI RecvMsg(void* arg) { //1 Receive the parameters passed in SOCKET hClntSock = *((SOCKET*)arg); char szNameMsg[NAME_SIZE + BUF_SIZE]; // Another name , News again int iLen = 0; while (1) { //recv Blocking iLen = recv(hClntSock, szNameMsg, NAME_SIZE + BUF_SIZE - 1, 0); // The server is disconnected if (iLen == -1) { return -1; } // szNameMsg Of 0 To iLen -1 All the data received iLen individual szNameMsg[iLen] = 0; // The received data is output to the console fputs(szNameMsg, stdout); } return 0; } int main(int argc,char *argv[]) { WORD wVersionRequested; WSADATA wsaData; int err; SOCKET hSock; SOCKADDR_IN servAdr; HANDLE hSendThread, hRecvThread; wVersionRequested = MAKEWORD(1, 1); // Initialize socket library err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return err; } if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); return -1; } sprintf(szName, "[%s]", argv[1]); //1 establish socket hSock = socket(PF_INET, SOCK_STREAM, 0); // 2 Configure ports and addresses memset(&servAdr, 0, sizeof(servAdr)); inet_pton(AF_INET, "192.168.10.3", &servAdr.sin_addr); //servAdr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); servAdr.sin_family = AF_INET; servAdr.sin_port = htons(9999); // 3 Connect to server if (connect(hSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR) { printf("connect error error code = %d\n", GetLastError()); return -1; } hSendThread = (HANDLE)_beginthreadex(NULL, 0, SendMsg, (void*)&hSock, 0, NULL); // 5 Receive messages to the server Arrange a worker Start a thread to receive messages hRecvThread = (HANDLE)_beginthreadex(NULL, 0, RecvMsg, (void*)&hSock, 0, NULL); // Wait for the signal of the kernel object to change WaitForSingleObject(hSendThread, INFINITE); WaitForSingleObject(hRecvThread, INFINITE); // 6 Close socket closesocket(hSock); WSACleanup(); return 0; }
Server code
#include<stdio.h> #include<windows.h> #include<process.h> #pragma comment(lib, "ws2_32.lib") #define MAX_CLNT 256 #define MAX_BUF_SIZE 256 SOCKET clntSocks[MAX_CLNT]; // All connected clients socket HANDLE hMutex; int clntCnt = 0; // Number of current connections void SendMsg(char* szMsg, int iLen) { int i = 0; WaitForSingleObject(hMutex, INFINITE); for (i = 0; i < clntCnt; i++) { send(clntSocks[i], szMsg, iLen, 0); } ReleaseMutex(hMutex); } unsigned WINAPI HandleCln(void* arg) { SOCKET hClntSock = *((SOCKET*)arg); int iLen = 0, i; char szMsg[MAX_BUF_SIZE] = { 0 }; while (1) { iLen = recv(hClntSock, szMsg, sizeof(szMsg), 0); if (iLen != -1) { // The received data is immediately sent to all clients SendMsg(szMsg, iLen); } else { break; } } printf(" At this time, the number of connections is %d\n", clntCnt); //3 A connection is disconnected , Need to handle disconnected connections Traverse WaitForSingleObject(hMutex, INFINITE); for (i = 0; i < clntCnt; i++) { if (hClntSock == clntSocks[i]) { // displacement while (i++ < clntCnt) { clntSocks[i] = clntSocks[i + 1]; } break; } } clntCnt--; // A self subtraction of the current number of connections printf(" Disconnect the number of connections at this time %d", clntCnt); ReleaseMutex(hMutex); closesocket(hClntSock); return 0; } int main() { // Load socket library WORD wVersionRequested; WSADATA wsaData; int err; HANDLE hThread; wVersionRequested = MAKEWORD(1, 1); // Initialize socket library err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return err; } if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); return -1; } // Create a mutex hMutex = CreateMutex(NULL, FALSE, NULL); // New socket SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(9999); // Bind socket to local IP Address , Port number 9190 if (bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) == SOCKET_ERROR) { printf("bind ERRORnum = %d\n", GetLastError()); return -1; } // Start listening if (listen(sockSrv, 5) == SOCKET_ERROR) { printf("listen ERRORnum = %d\n", GetLastError()); return -1; } printf("start listen\n"); SOCKADDR_IN addrCli; int len = sizeof(SOCKADDR); while (1) { // Receive customer connections sockConn At this time, the client connection SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrCli, &len); WaitForSingleObject(hMutex, INFINITE); clntSocks[clntCnt++] = sockConn; ReleaseMutex(hMutex); hThread = (HANDLE)_beginthreadex(NULL, 0, HandleCln, (void*)&sockConn, 0, NULL); printf("Connect client IP: %s \n", inet_ntoa(addrCli.sin_addr)); printf("Connect client num: %d \n", clntCnt); } closesocket(sockSrv); WSACleanup(); return 0; }
边栏推荐
- 苹果 5G 芯片研发失败?想要摆脱高通为时过早
- Learning notes 5 - high precision map solution
- 橫向滾動的RecycleView一屏顯示五個半,低於五個平均分布
- 程序员搞开源,读什么书最合适?
- @SerializedName注解使用
- 天龙八部TLBB系列 - 关于技能冷却和攻击范围数量的问题
- Glide advanced level
- 面试:List 如何根据对象的属性去重?
- AtCoder Beginner Contest 254「E bfs」「F st表维护差分数组gcd」
- Have you learned to make money in Dingding, enterprise micro and Feishu?
猜你喜欢

Learning II of workmanager

Design of stepping motor controller based on single chip microcomputer (forward rotation and reverse rotation indicator gear)

SAP UI5 ObjectPageLayout 控件使用方法分享

Fluent generates icon prompt logo widget

MySQL character type learning notes

What is the origin of the domain knowledge network that drives the new idea of manufacturing industry upgrading?

Solution of ellipsis when pytorch outputs tensor (output tensor completely)

【小技巧】獲取matlab中cdfplot函數的x軸,y軸的數值

重磅:国产IDE发布,由阿里研发,完全开源!

Constraintlayout officially provides rounded imagefilterview
随机推荐
面试:List 如何根据对象的属性去重?
官网给的这个依赖是不是应该为flink-sql-connector-mysql-cdc啊,加了依赖调
《剑来》语句摘录(七)
ConstraintLayout的流式布局Flow
SLAM 01.人类识别环境&路径的模型建立
程序员搞开源,读什么书最合适?
Glide conclusion
Excerpt from "sword comes" (VII)
WorkManager学习一
Cerebral cortex: directed brain connection recognition widespread functional network abnormalities in Parkinson's disease
Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~
学习笔记6--卫星定位技术(上)
The horizontally scrolling recycleview displays five and a half on one screen, lower than the average distribution of five
In wechat applet, after jumping from one page to another, I found that the page scrolled synchronously after returning
Glide advanced level
【观察】跨境电商“独立站”模式崛起,如何抓住下一个红利爆发时代?
QT VT100 parser
Shortcut keys for vscode
字节跳动面试官:一张图片占据的内存大小是如何计算
各位大佬,我测试起了3条线程同时往3个mysql表中写入,每条线程分别写入100000条数据,用了f