socket聊天室
原文地址:https://blog.csdn.net/xiaoquantouer/article/details/58001960
服務端
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <stdio.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") //加載ws2_32.lib庫int main(int argc, char *argv[]) {//加載套接字WORD sockVersion = MAKEWORD(2, 2);//指定socket版本2.2WSADATA wsaData;//存儲被WSAStartup函數調用后返回的Windows Sockets數據if (WSAStartup(sockVersion, &wsaData) != 0) return 0;//創建服務端socket,三個參數分別代表IP地址族,流式套接字,TCP協議SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (slisten == INVALID_SOCKET){printf("socket error!");return 0;}//綁定服務端ip和端口sockaddr_in sin;//存放了地址族、端口、ip地址,用來處理通信地址sin.sin_family = AF_INET;//ip地址族sin.sin_port = htons(8888);//轉換網絡編碼,偵聽本地8888端口sin.sin_addr.S_un.S_addr = INADDR_ANY;//接收任意地址的連接if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR){printf("bind error!");}//開始偵聽if (listen(slisten, 5) == SOCKET_ERROR){printf("listen error!");return 0;}SOCKET sClient;//創建客戶端socketsockaddr_in remoteAddr;//客戶端的地址信息int nAddrlen = sizeof(remoteAddr);char revData[255];//接收數據緩沖區//循環接收數據while (1){printf("waiting...\n");//等待連接,返回客戶端socketsClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);if (sClient == INVALID_SOCKET){printf("accept error!");continue;}printf("Connection successful:%s\n", inet_ntoa(remoteAddr.sin_addr));//接收數據int ret = recv(sClient, revData, 255, 0);//若無錯誤,返回讀入字節數if (ret > 0){revData[ret] = '\0';printf("%s\n", revData);}//發送數據char sendData[255];gets_s(sendData);send(sClient, sendData, strlen(sendData), 0);closesocket(sClient);}closesocket(slisten);//關閉服務端socketWSACleanup();return 0; }客戶端
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include<winsock2.h> #include<stdio.h> #pragma comment(lib, "ws2_32.lib") int main() {WORD sockVersion = MAKEWORD(2, 2);WSADATA data;if (WSAStartup(sockVersion, &data) != 0) return 0;while (true) {SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (sclient == INVALID_SOCKET){printf("invalid socket!");return 0;}sockaddr_in serAddr;//處理服務端地址的結構,包含地址族、端口、ip地址serAddr.sin_family = AF_INET;//IP地址族serAddr.sin_port = htons(8888);//服務端端口serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//服務端ipif (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR){printf("connect error !");closesocket(sclient);return 0;}//發送數據char sendData[255];gets_s(sendData);send(sclient, sendData, strlen(sendData), 0); //接收數據char recData[255];int ret = recv(sclient, recData, 255, 0);if (ret>0) {recData[ret] = '\0';printf(recData);}closesocket(sclient);}WSACleanup();return 0; }總結
- 上一篇: 函数指针和shellcode
- 下一篇: 将JPG文件作为EXE执行