将写代码过程中经常用到的一些代码段珍藏起来,下边资料是关于C++ TCP winsock 多线程编程的代码,希望能对各位也有好处。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
#define PORT 4000
#define IP_ADDRESS "127.0.0.1"
DWORD WINAPI ClientThread (LPVOID ipParameter)
{
SOCKET ClientScoket = (SOCKET)ipParameter;
int RET = 0;
char RecvBuffer[MAX_PATH];
while(true){
memset(RecvBuffer,0x00,sizeof(RecvBuffer));
RET = recv(ClientScoket,RecvBuffer,MAX_PATH,0);
if(RET == 0||RET == SOCKET_ERROR)
{
cout<<"failed,exit"<<endl;
break;
}
cout<<"接受的消息为"<<RecvBuffer<<endl;
}
return 0;
}
int main(void)
{
WSADATA WSA;
SOCKET severScoket,clientScoket;
struct sockaddr_in LocalAddr,clientAddr;
int AddrLen = 0;
HANDLE hThread = NULL;
int RET = 0;
if (WSAStartup(MAKEWORD(2,2),&WSA)!= 0 )
{
cout<<"init failed"<<endl;
return -1;
}
severScoket = socket(AF_INET,SOCK_STREAM,0);
if(severScoket == INVALID_SOCKET)
{
cout<<"creat failed"<<GetLastError()<<endl;
return -1;
}
LocalAddr.sin_family = AF_INET;
LocalAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
LocalAddr.sin_port = htons(PORT);
memset(LocalAddr.sin_zero,0x00,8);
if (RET != 0)
{
cout<<"bind failed";
return -1;
}
RET = listen(severScoket,5);
if (RET!= 0)
{
cout<<"listen failed";
return -1;
}
cout<<"服务器已启动"<<endl;
while(true)
{
AddrLen = sizeof(clientAddr);
if (clientScoket ==INVALID_SOCKET)
{
cout<<"accept failed";
break;
}
cout<<"客户端连接"<<inet_ntoa(clientAddr.sin_addr)<<"."<<clientAddr.sin_port<<endl;
hThread = CreateThread(NULL,0,ClientThread,(LPVOID)clientScoket,0,NULL);
if(hThread == NULL)
{
cout<<"creat thread failed"<<endl;
break;
}
CloseHandle(hThread);
}
closesocket(severScoket);
closesocket(clientScoket);
WSACleanup();
return 0;
}
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
#define PORT 4000
#define IP_ADDRESS "127.0.0.1"
int main(void)
{
WSADATA WSA;
SOCKET clientScoket;
struct sockaddr_in serveAddr;
int AddrLen = 0;
HANDLE hThread = NULL;
int RET = 0;
char SendBuffer[MAX_PATH];
if (WSAStartup(MAKEWORD(2,2),&WSA)!= 0 )
{
cout<<"init failed"<<endl;
return -1;
}
clientScoket = socket(AF_INET,SOCK_STREAM,0);
if(clientScoket == INVALID_SOCKET)
{
cout<<"creat failed"<<GetLastError()<<endl;
return -1;
}
serveAddr.sin_family = AF_INET;
serveAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
serveAddr.sin_port = htons(PORT);
memset(serveAddr.sin_zero,0x00,8);
if (RET != 0)
{
cout<<"connect failed";
return -1;
}
else{ cout<<"链接成攻"<<endl;}
while(true)
{
cin.getline(SendBuffer,sizeof(SendBuffer));
RET = send(clientScoket,SendBuffer,(int)strlen(SendBuffer),0);
if (RET == SOCKET_ERROR)
{
cout<<"send to error"<<endl;
break;
}
}
closesocket(clientScoket);
WSACleanup();
return 0;
}
原文地址:https://blog.51cto.com/14122754/2382428