简易聊天程序

时间:2019-03-12 08:42:11
【文件属性】:

文件名称:简易聊天程序

文件大小:5.1MB

文件格式:ZIP

更新时间:2019-03-12 08:42:11

windowsAPI win32 SOKCET

自己写的小小小程序,能实现简单的通信 // Client.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include #include #include "Thread.h" #pragma comment(lib,"ws2_32.lib") #define PORT 4567 #define BUFFERMAX 256 CRITICAL_SECTION cs; int main() { WSADATA wsaData; WORD sockVersion = MAKEWORD(2, 2); if (WSAStartup(sockVersion, &wsaData) != 0) { std::cout << "Initlization failed" << std::endl; system("pause"); return 0; } SOCKET clientSocket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (clientSocket == INVALID_SOCKET) { std::cout << "Failed socket!"<< std::endl; system("pause"); return 0; } sockaddr_in serverSockAddr; serverSockAddr.sin_family = AF_INET; serverSockAddr.sin_port = htons(PORT); InetPton(AF_INET,_T("127.0.0.1"),&(serverSockAddr.sin_addr.S_un.S_addr)); if (connect(clientSocket, (sockaddr*)&serverSockAddr, sizeof(sockaddr))) { std::cout << "Connect failed!" << std::endl; } InitializeCriticalSection(&cs); connection(clientSocket, (sockaddr*)&serverSockAddr); char * sendData = "你好,TCP服务端,我是客户端!\n"; send(clientSocket, sendData, strlen(sendData), 0); //volatile int connect_flag = 0; sock_Attribute sock_R = { clientSocket,0,&serverSockAddr}; sock_Attribute sock_S = { clientSocket,0,&serverSockAddr}; HANDLE hdll = CreateThread(NULL, 0, recv_Thread, &sock_R, 0, 0); if (hdll == nullptr) { std::cout << "创建线程失败" << std::endl; } send_Thread(&sock_S); system("pause"); DeleteCriticalSection(&cs); closesocket(clientSocket); WSACleanup(); return 0; } DWORD WSAAPI recv_Thread(LPVOID P) //不加 WSAAPI 关键字会报错,可能跟调用方式有关 { char recvBuffer[BUFFERMAX] = "\0"; int nRecv; int size = sizeof(recvBuffer); sock_Attribute* pSock = (sock_Attribute*)P; for (;;) { nRecv = recv(pSock->s, recvBuffer, size, pSock->flags); if (nRecv == SOCKET_ERROR||nRecv ==0) { connection(pSock->s, (sockaddr*)(pSock->serverAddr)); //break; } if(nRecv>0) { if (recvBuffer != '\0') // '\0' 即 NULL { std::cout << "Client : " << recvBuffer << std::endl; //*recvBuffer = NULL; memset(recvBuffer, 0x00, size); /* 字符串用字符串函数操作, 数组用指针操作,*/ } } } return 0; } DWORD WSAAPI send_Thread(LPVOID P) { sock_Attribute* pSock = (sock_Attribute*)P; char sendBuffer[BUFFERMAX] = "\0"; int size = sizeof(sendBuffer); for (;;) { std::cin.getline(sendBuffer, size); switch (send(pSock->s, sendBuffer,size, pSock->flags)) { case SOCKET_ERROR: { connection(pSock->s, (sockaddr*)(pSock->serverAddr)); break; } default: break; } } return 0; }


网友评论