开发工具:
文件大小: 5mb
下载次数: 0
上传时间: 2016-02-20
详细说明: 自己写的小小小程序,能实现简单的通信 // 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; } ...展开收缩
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.