想要应聘c++后端开发岗,网络编程非常重要,学习这个过程也是非常享受的事,本文简单实现了回声(Echo)服务端和客户端,没有涉及多线程并发,是一个比较简单的学习例程。
参考:
1、 C++:实现socket通信(TCP/IP)实例
2、《TCP IP网络编程》(韩)尹圣雨
3、TCP/IP协议详解
服务端代码
服务端创建日志文本存储日志,并于while(true)中死循环等待客户端连接。
#include "pch.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include<winsock.h>
#include <string>
#include "time.h"
//使用localtime
#pragma warning(disable:4996)
//使用套接字库
#pragma comment(lib,"ws2_32.lib")
using namespace std;
string timetoStr() {
char tmp[64];
time_t t = time(NULL);
tm *_tm = localtime(&t);
int year = _tm->tm_year + 1900;
int month = _tm->tm_mon + 1;
int date = _tm->tm_mday;
int hh = _tm->tm_hour;
int mm = _tm->tm_min;
int ss = _tm->tm_sec;
sprintf(tmp, "%04d%02d%02d %02d:%02d:%02d ", year, month, date, hh, mm, ss);
return string(tmp);
}
string GetLogNameByDate() {
char tmp[30];
time_t t = time(NULL);
tm *_tm = localtime(&t);
int year = _tm->tm_year + 1900;
int month = _tm->tm_mon + 1;
int date = _tm->tm_mday;
sprintf(tmp, "%04d%02d%02d.txt", year, month, date);
return string(tmp);
}
void ErrorHandling(