本代码是windows系统环境c++(c) socket编程实例。包含客户端和服务端,可以实现客户端发送消息,服务端接收消息并写入日志。 server.cpp为服务端。 client.cpp为客户端。
服务端代码server.cpp:
//by whg 2018-5-23
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include<iostream>
#include<WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#define CONNECT_NUM_MAX 10
using namespace std;
//日志记录
int write_log (char *format) {
FILE* pFile = fopen("e:\\log.txt", "a");
fprintf(pFile, "recv:%s\n",format);
fflush(pFile);
fclose(pFile);
return 1;
}
int main()
{
//加载套接字库
WSADATA wsaData;
int iRet = 0;
iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iRet != 0)
{
cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;;
return -1;
}
if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
{
WSACleanup();
cout <<