学习一个月web开发的成果,服务器C++的select模型,数据库postgresql,前台html,css,js jquery做的简易的知识分享平台,有注册,登录,知识分享(类似博文),知识浏览,知识维护,留言板。做为新手学习这个真是很痛苦,资料也不多,分享下一起学习吧!后续继续努力。公司沙盒东西带不走,就放这里以后自己也看看菜鸟时候写的东西。。
为了方便看都放一个文件里了,见谅,代码3000多行,后续会继续学习WEB开发技术完善这个程序
#include
#pragma comment(lib, "ws2_32.lib")
#include
#include
#include
#include"server.h"
#include
#include
#include
#include
#include"libpq-fe.h"
using namespace std;
int totalSockets = 0;//socket的总数
string logBuff;//写日志字符数组
char CustomHtml[100000];//发送html数组
struct socketStu
{
SOCKET s_socket;
USHORT uPort;
IN_ADDR ipAddress;
bool isOk;//是否有效 1you 0wu
};
struct socketStu socketArray[1000];
//用于保存清楚无效socket后的数组
struct socketStu_new
{
SOCKET s_socket;
USHORT uPort;
IN_ADDR ipAddress;
bool isOk;//是否有效 1you 0wu
//socketStu(SOCKET s,bool ok) :s_socket(s), isOk(ok){}
};
struct socketStu_new socketArray_new[1000];
//日志保存函数
void log(string pStr)
{
char timenow[50];
char strConv[1024];
memset(timenow, 0, sizeof(timenow));
memset(strConv, 0, sizeof(strConv));
SYSTEMTIME time;
GetLocalTime(&time);
sprintf_s(timenow, sizeof(timenow), "%d:%d:%d:%d:%d:%d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
ofstream savelog("log.txt", ios::out);
if (!savelog){
cout << "open file error!" << endl;
exit(1);
}
logBuff += pStr;
logBuff += timenow;
logBuff += "\n";
//字符串转字符数组
strcpy_s(strConv, logBuff.c_str());
savelog.write(strConv, strlen(strConv));//写入log.txt
savelog.close();
}
//UTF-8到GB2312的转换
char* U2G(const char* utf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
if (wstr) delete[] wstr;
return str;
}
char* G2U(const char* gb2312)
{
int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
if (wstr) delete[] wstr;
return str;
}
//保存socket信息
void addToSocketArr(const SOCKET & s, const in_addr & ipaddress, const USHORT & uport)
{
//new socketStu(s, 1);
socketArray[totalSockets].s_socket = s;
socketArray[totalSockets].ipAddress = ipaddress;//ip地址
socketArray[totalSockets].uPort = uport;//端口号
socketArray[totalSockets].isOk = yes;//默认有效
totalSockets++;
}
//创建监听套接字
SOCKET getListenSocket(){
//创建监听socket
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocket == INVALID_SOCKET){
cout << "creat socket fail,the error code:" << endl;
WSACleanup();
return 0;
}
//服务地信息
SOCKADDR_IN srvAddr;
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//srvAddr.sin_addr.s_addr = inet_addr("192.168.24.49");
srvAddr.sin_port = htons(75);
//绑定
if (bind(listenSocket, (SOCKADDR*)&srvAddr, sizeof(srvAddr))){
cout << "bind socket fail,the error code:" << GetLastError() << endl;
WSACleanup();
return 0;
}
//监听
if (listen(listenSocket, 5)){
cout << "listen fail,the error code:" << GetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
}
//设置socket为非阻塞模式
unsigned long nonBlock = 1;
if (ioctlsocket(listenSocket, FIONBIO, &nonBlock) == SOCKET_ERROR){
cout << "set socket async fail " << GetLastError() << endl;
closesocket(listenSocket);
WSACleanup();
}
addToSocketArr(listenSocket, srvAddr.sin_addr, srvAddr.sin_port);//添加到socket数组中
return listenSocket;
}
char * Wchar_tToString(wchar_t *wchar)
{
wchar_t * wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);// WideCharToMultiByte的运用
char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
psText = new char[dwNum];
WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);// WideCharToMultiByte的再次运用
return psText;
}
string tansForm(string str){
char utf8[1024] = { 0 };
strcpy_s(utf8, str.c_str());
int len = strlen(utf8);
char * delFuhao = new char[len + 1];
memset(delFuhao, 0, sizeof(delFuhao));
int pos = 0;
string strTransform;
//去掉%
for (int i = 0; i < len; i++){
if (utf8[i] != '%'){
delFuhao[pos] = utf8[i];
pos++;
}
}
delFuhao[pos] = '\0';
int l1 = strlen(delFuhao);
int UTF8len = l1 / 2;
char * utfstr = new char[UTF8len + 1];
for (int i = 0; i < UTF8len * 2;)
{
char convert[3] = { 0 };
convert[0] = delFuhao[i++];
convert[1] = delFuhao[i++];
char *end;
int tempint = strtol(convert, &end, 16);
utfstr[i / 2 - 1] = tempint;
}
//UTF8转换到UTF16
int wcslen1 = ::MultiByteToWideChar(CP_UTF8, NULL, utfstr, UTF8len, NULL, 0);
wchar_t* wszString = new wchar_t[wcslen1 + 1];
::MultiByteToWideChar(CP_UTF8, NULL, utfstr, UTF8len, wszString, wcslen1);
wszString[wcslen1] = L'\0';
//设置区域
std::wcout.imbue(std::locale("CHS"));
//return wszString;
//w_char to string
if (wcslen(wszString) != 0){
strTransform = Wchar_tToString(wszString);
}
return strTransform;
}
string messageForReady(IN_ADDR ipaddress,USHORT uPort){
string Readystr;
string ipAddress;
char uport[20] = { 0 };
string portid;
SYSTEMTIME time;
//GetSystemTime(&time);
GetLocalTime(&time);
//设置GMT时间格式
//time_t t = time(NULL);
//char szBuf[128] = { 0 };
//tm ttt = {0};
//gmtime_s(struct tm * _Tm, const time_t * _Time)
//strftime(szBuf, sizeof(szBuf), "%A,%d-%b-%y %H:%M:%S", gmtime_s(&ttt,&t));
char timenow[50] = { 0 };
sprintf_s(timenow, sizeof(timenow), "%d-%d-%d %d:%d:%d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
string timefinal;
timefinal = string(timenow);
Readystr += "[";
Readystr += "time: ";
Readystr += timefinal;
Readystr += " ";
ipAddress = inet_ntoa(ipaddress);
//ipAddress = htons();
Readystr += "ip: ";
Readystr += ipAddress;
Readystr += " ";
_itoa_s(uPort, uport, sizeof(uport), 10);//ushort to string
portid = string(uport);
Readystr += "port: ";
Readystr += portid;
Readystr += "]";
Readystr += "\n";
return Readystr;
}
//写数据库
void insertDBMessage(const IN_ADDR ipaddress, USHORT uport, string & tempTotal, string & str2){
char uportid[20] = { 0 };
//strcpy_s(temptotal,tempTotal.c_str());
_itoa_s(uport, uportid, sizeof(uportid), 10);
char connectpresql[128];
sprintf_s(connectpresql, "dbname=postgres user=postgres password=123456");
PGconn *pcon;
pcon = PQconnectdb(connectpresql);
PGresult *res;
if (PQstatus(pcon) != CONNECTION_OK){
cout << "insert db:connect to db fail!" << endl;
}
//提取时间
int timepos = tempTotal.find("time:");
char storetime[128] = {0};
if (timepos > 0){
int k = 0;
for (int j = timepos + 6; j
k++;
}
}
else
{
cout << "insert db:can't find time,please check it out!";
}
char tempstr[1024];
memset(tempstr, 0, sizeof(tempstr));
//setlocale(LC_ALL,"");
PQsetClientEncoding(pcon, "GBK");
sprintf_s(tempstr, sizeof(tempstr), "insert into storemessage(ipaddress,port,message,messagetime) values('%s','%s','%s','%s')", inet_ntoa(ipaddress), uportid, str2.c_str(), storetime);
pg_char_to_encoding("utf-8");
res = PQexec(pcon, tempstr);
char * k = PQcmdTuples(res);
if (*k < 1){
cout << "insert DB:insert fail!" << PQerrorMessage(pcon)<< endl;
PQfinish(pcon);
PQclear(res);
}
else{
cout << "insert DB:insert successfully!insert num:" << *k;
PQfinish(pcon);
PQclear(res);
}
}
//主体
void Main_Work(SOCKET & listenSocket){
char finalstr[1024];
memset(finalstr, 0, sizeof(finalstr));
char tempBuff[1024];
int forwardshow = NULL;
int forward = NULL;
int forward2 = NULL;
string requestHtmlStr;//判断请求
int forwardRegisSuccess = NULL;
int forwardLoginSuc = NULL;
int forwardLoginfail = NULL;
int forwardIDdup = NULL;
int forwardArticleSuccess = NULL;
int checkUseridDul = NULL;
int forwardIDdupError = NULL;
int forwardasktoLogin = NULL;
int forwardSubmitActicle = NULL;//发文章
memset(tempBuff, 0, sizeof(tempBuff));
string finalStrTrans;
wchar_t *transUtf8 = NULL;
wchar_t transUtf8Total[1024] = { 0 };
int x = 1;
string showDBStr;//数据库提取构造表
char recvBuff[99999];//接收请求头
while (1){
//初始化read write except
FD_SET readSet;
FD_SET writeSet;
FD_SET exceptSet;
FD_ZERO(&readSet);
FD_ZERO(&writeSet);
FD_ZERO(&exceptSet);
SOCKET acceptSocket = 0;
forwardshow = NULL;//转到show页面
forwardRegisSuccess = NULL;//注册
forwardLoginSuc = NULL;//登录
forward = NULL;//初始页面
forward2 = NULL;//成功页面
forwardLoginSuc = NULL; //注册
forwardLoginfail = NULL;
transUtf8 = NULL;
forwardasktoLogin = NULL;
forwardIDdup = NULL;
forwardArticleSuccess = NULL;
forwardSubmitActicle = NULL;
requestHtmlStr= "";//判断请求
finalStrTrans = "";
memset(transUtf8Total, 0, sizeof(transUtf8Total));
//添加readSet,writeSet,exceptSet
for (int j = 0; j < totalSockets; j++){
//如果无效删除
if (socketArray[j].isOk == 0){
for (int k = j; k < totalSockets; k++){
socketArray[k] = socketArray[k + 1];
}
totalSockets -= 1;
}
else{
continue;
}
}
for (int i = 0; i < totalSockets; i++){
FD_SET(socketArray[i].s_socket, &readSet);
FD_SET(socketArray[i].s_socket, &writeSet);
FD_SET(socketArray[i].s_socket, &exceptSet);
}
//timeval time;
//time.tv_sec = 60;//60秒等待时间
int total = select(0, &readSet, &writeSet, &exceptSet, NULL);//最后一个参数设置等待时间
if (total < 0){
cout << "client is closed ,the error code:" << GetLastError() << endl;
continue;
}
else if (total == 0){
cout << "第" << x << "次等待超时" << endl;
if (x < 3)
{
x++;
continue;
}
else
{
cout << "超过等待限制,服务器将关闭\n" << endl;
break;
}
}
else{
for (int p = 0; p < totalSockets; p++){
///forward = NULL;
//forward2 = NULL;
//forwardshow = NULL;
//cout <<"ip:" << inet_ntoa(socketArray[i].ipAddress) <<"port:"<< socketArray[i].uPort << endl;
//如果当前socket是监听socket
if (socketArray[p].s_socket == listenSocket){
//判断当前监听socket是否异常
if (FD_ISSET(listenSocket, &exceptSet)){
int error = 0;
int errlen = sizeof(error);
memset(CustomHtml, 0, sizeof(CustomHtml));
getsockopt(listenSocket, SOL_SOCKET, SO_ERROR, (char *)error, &errlen);
cout << "server detect listen socket exception,server will close.." << error;
ifstream infile("listenSocketErr.htm", ios::in | ios::_Nocreate);
infile.read(CustomHtml, sizeof(CustomHtml));
infile.close();
//客户端发送错误html
send(listenSocket, CustomHtml, strlen(CustomHtml), 0);
closesocket(listenSocket);
WSACleanup();
exit(1);//关闭服务器
}
//有客户端访问
if (FD_ISSET(listenSocket, &readSet))
{
acceptSocket = 0;
//如果超出最大连接数提示
if (totalSockets > FD_SETSIZE - 1){
cout << "The number of clients beyond the max num,connect fail";
continue;
}
//接收来自于客户端的connect请求
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
acceptSocket = accept(listenSocket, (SOCKADDR*)&addrClient, &len);
if (acceptSocket == INVALID_SOCKET&&acceptSocket != WSAEWOULDBLOCK){
cout << "connection fail!" << GetLastError() << endl;
continue;
}
else{
//cout << "new connection socket:" << acceptSocket << endl;
//将新套接字设置为非阻塞模式
u_long nonBlock = 1;
if (ioctlsocket(acceptSocket, FIONBIO, &nonBlock) == SOCKET_ERROR){
cout << "set socket async fail,the error code: " << GetLastError() << endl;
closesocket(acceptSocket);
WSACleanup();
}
addToSocketArr(acceptSocket, addrClient.sin_addr, addrClient.sin_port);//添加到socket数组中
}
}
}
//该socket不是监听socket
else{
if (FD_ISSET(socketArray[p].s_socket, &readSet)){
string recvBuffStr;
memset(recvBuff, 0, sizeof(recvBuff));
memset(tempBuff, 0, sizeof(tempBuff));
int recvNum = recv(socketArray[p].s_socket, recvBuff, sizeof(recvBuff), 0);
cout << recvBuff;//11111111111测试请求头
if (recvNum == SOCKET_ERROR){
cout << "socket id:" << socketArray[p].s_socket << "lose connect" << endl;
socketArray[p].isOk = 0;
closesocket(socketArray[p].s_socket);
continue;
}
if (recvNum == 0){
socketArray[p].isOk = 0;
cout << "lose connect" << endl;
continue;
}
if (recvNum < 0){
socketArray[p].isOk = 0;
cout << "recv error" << GetLastError() << endl;
continue;
}
recvBuffStr = string(recvBuff);
int index = recvBuffStr.find("message");
int indexShow = recvBuffStr.find("showButton");
int indexReturn = recvBuffStr.find("sendButtonReturn");
int submitRegister = recvBuffStr.find("submitRegister");//注册
int loginSystem = recvBuffStr.find("loginSystem");//登录
int submitActicle = recvBuffStr.find("submitArticle");//发表文章
int idIndex = recvBuffStr.find("btnid");
//页面初始化
if (indexShow < 0 && index <0&&indexReturn<0){
forward = 1;
}
//用户id重复
if (indexShow < 0 && index < 0 && indexReturn < 0 && submitRegister < 0 && loginSystem<0){
if (idIndex>0){
forward = 0;
checkUseridDul = 1;
}
else{
forward = 1;
}
}
//处理showMessage按钮
if (indexShow > 0){
//cout << "showButton is clicked~!" << endl;
index = NULL;
forward = NULL;
forward2 = NULL;
forwardshow = 1;
}
//处理注册按钮
if (submitRegister > 0){
index = NULL;
forward = NULL;
forward2 = NULL;
forwardRegisSuccess = 1;
}
//登录
if (loginSystem > 0){
index = NULL;
forward = NULL;
forward2 = NULL;
forwardLoginSuc = 1;
}
//发表文章
if (submitActicle > 0){
index = NULL;
forward = NULL;
forward2 = NULL;
forwardSubmitActicle = 1;
}
if (index > 0){
forwardshow = NULL;
forward = NULL;
forward2 = 1;//测试
}
if (indexReturn > 0){
forward2 = NULL;
forwardshow = NULL;
forward = 1;
}
//处理sendMessage按钮开始
if (index > 0 && indexShow < 0){
int j = 0;
//提取需要的数据
for (int i = index + 8; i < recvBuffStr.length(); i++){
tempBuff[j] = recvBuffStr[i];
j++;
}
if (strlen(tempBuff) == 0){
cout << "no submition now..." << endl;
}
else
{
string str1;
string str2;
string zimu;
string temp1;
string trans;
index = NULL;
forward = NULL;
forwardshow = NULL;
forward2 = 1;//跳向成功页面
memset(finalstr, 0, sizeof(finalstr));
string temp;
temp = string(tempBuff);
//如果有+号,转换数据在finalstr中,多空格处理
int addsearch = temp.find("+");
if (addsearch > 0){
for (int i = 0; i < strlen(tempBuff); i++){
if (tempBuff[i] == '+'){
tempBuff[i] = ' ';
}
continue;
}
//string utf8Str = string(utf8);
for (int i = 0; i < strlen(tempBuff);){
str1 = "";
temp1 = "";
//zimu = "";
if (tempBuff[i] == '%'){
temp1 = temp.substr(i, 3);
trans += temp1;
i += 3;
continue;
}
else if (tempBuff[i] >= 'a'&&tempBuff[i] <= 'z'){
zimu += tempBuff[i];
i++;
if (tempBuff[i] != '%'){
continue;
}
else{
str1 = tansForm(trans);
str2 += str1;
str2 += zimu;
trans = "";
zimu = "";
}
}
else if (tempBuff[i] >= 'A'&&tempBuff[i] <= 'Z'){
zimu += tempBuff[i];
i++;
if (tempBuff[i] != '%'){
continue;
}
else{
str1 = tansForm(trans);
str2 += str1;
str2 += zimu;
trans = "";
zimu = "";
}
}
else if (tempBuff[i] >= '0'&&tempBuff[i] <= '9'){
zimu += tempBuff[i];
i++;
if (tempBuff[i] != '%'){
continue;
}
else{
str1 = tansForm(trans);
if (str1.length() != 0){
str2 += str1;
trans = "";
i++;
}
else{
str2 += zimu;
zimu = "";
trans = "";
//i++;
}
}
}
else if (tempBuff[i] == ' '){
str1 = tansForm(trans);
if (str1.length() != 0){
if (zimu.length()!=0){
str2 += str1;
str2 += zimu;
str2 += ' ';
trans = "";
zimu = "";
i++;
}
else{
str2 += str1;
str2 += ' ';
trans = "";
i++;
}
}
else{
if (zimu.length() != 0){
zimu += ' ';
str2 += zimu;
zimu = "";
i++;
}
else{
zimu += ' ';
str2 += zimu;
zimu = "";
trans = "";
i++;
}
//i++;
}
}
}
str1 = tansForm(trans);
str2 += str1;
str2 += zimu;
trans = "";
zimu = "";
//break;
showStr += str2;
cout << "recv from client:" << str2 << endl;
string tempTotal;
tempTotal = messageForReady(socketArray[p].ipAddress, socketArray[p].uPort);
showStr += tempTotal;
forward = NULL;
forward2 = 1;
//写入数据库
insertDBMessage(socketArray[p].ipAddress, socketArray[p].uPort,tempTotal,str2);
//break;
}//+号
else{
//string str1;
//string str2;
//string zimu;
//string temp1;
//string trans;
//找串中是否有%
for (int i = 0; i < strlen(tempBuff); i++){
if (tempBuff[i] != '%'){
zimu += tempBuff[i];
continue;
if (i == strlen(tempBuff)){
showStr += temp;
cout << "recv from client:" << temp << endl;
string tempTotal;
tempTotal = messageForReady(socketArray[p].ipAddress, socketArray[p].uPort);
showStr += tempTotal;
//写入数据库
insertDBMessage(socketArray[p].ipAddress, socketArray[p].uPort, tempTotal, temp);
//break;
}
}
else{
int i = 0;
//string utf8Str = string(utf8);
for (i = 0; i < strlen(tempBuff);){
str1 = "";
temp1 = "";
//zimu = "";
if (tempBuff[i] == '%'){
temp1 = temp.substr(i, 3);
trans += temp1;
i += 3;
continue;
}
else if (tempBuff[i] >= 'a'&&tempBuff[i] <= 'z'){
zimu += tempBuff[i];
i++;
if (tempBuff[i] != '%'){
//i++;
continue;
}
else{
str1 = tansForm(trans);
str2 += str1;
str2 += zimu;
trans = "";
zimu = "";
}
}
else if (tempBuff[i] >= 'A'&&tempBuff[i] <= 'Z'){
zimu += tempBuff[i];
i++;
if (tempBuff[i] != '%'){
continue;
}
else{
str1 = tansForm(trans);
str2 += str1;
str2 += zimu;
trans = "";
zimu = "";
}
}
else if (tempBuff[i] >= '0'&&tempBuff[i] <= '9'){
zimu += tempBuff[i];
//i++;
if (tempBuff[i] != '%'){
i++;
continue;
}
else{
str1 = tansForm(trans);
if (str1.length() != 0){
if (zimu.length() != 0){
str2 += str1;
str2 += zimu;
zimu = "";
trans = "";
}
else{
str2 += str1;
trans = "";
}
}
else{
str2 += zimu;
zimu = "";
trans = "";
}
}
}
}
if (i == strlen(tempBuff)){
str1 = tansForm(trans);
str2 += str1;
str2 += zimu;
trans = "";
zimu = "";
//break;
}
showStr += str2;
cout << "recv from client:" << str2 << endl;
string tempTotal;
tempTotal = messageForReady(socketArray[p].ipAddress, socketArray[p].uPort);
showStr += tempTotal;
forward = NULL;
//写入数据库
insertDBMessage(socketArray[p].ipAddress, socketArray[p].uPort, tempTotal, str2);
break;
}
}
}
if (zimu.length() != 0){
str2 += zimu;
showStr += str2;
zimu = "";
cout << "recv from client:" << str2 << endl;
string tempTotal;
tempTotal = messageForReady(socketArray[p].ipAddress,socketArray[p].uPort);
showStr += tempTotal;
//写入数据库
insertDBMessage(socketArray[p].ipAddress, socketArray[p].uPort, tempTotal, str2);
}
forward = NULL;
forward2 = 1;
//break;
}
}
//处理sendMessage按钮结束
//处理注册开始
if (submitRegister > 0 || idIndex>0){
//if (forwardIDdupError == 1){
//socketArray[p].isOk = 0;
//closesocket(socketArray[p].s_socket);
//forwardIDdupError = NULL;
//break;
//}
string recvStr = string(recvBuff);
char getpost[10] = { 0 };
int y = 0;
for (int o = 0; o
break;
}
else{
getpost[y] = recvBuff[o];
y++;
}
}
if (checkUseridDul == 1){
//用户名是否重复校验
if (string(getpost) == "GET"){
int useridIndex = recvStr.find("userid");
char userId[128] = { 0 };
string userIdNum = "";
int g = 0;
for (int h = useridIndex + 7; h
break;
}
else{
userId[g] = recvBuff[h];
g++;
}
}
if (strlen(userId)>0){
userIdNum = string(userId);//提取传入的userid
char connectpresql[128];
sprintf_s(connectpresql, "dbname=postgres user=postgres password=123456");
PGconn *pcon;
pcon = PQconnectdb(connectpresql);
PGresult *res;
if (PQstatus(pcon) != CONNECTION_OK){
cout << "insert db:connect to db fail!" << endl;
}
char tempstrDB[1024] = { 0 };
PQsetClientEncoding(pcon, "GBK");
sprintf_s(tempstrDB, sizeof(tempstrDB), "SELECT username,userpassword FROM userinfo where username = '%s'", userIdNum.c_str());
res = PQexec(pcon, tempstrDB);
char * k = PQcmdTuples(res);
char * u_name;
char * u_pass;
if (PQresultStatus(res) == PGRES_TUPLES_OK&&PQntuples(res) > 0){
u_name = PQgetvalue(res, 0, 0);
//用户id重复
if (userIdNum == u_name){
forwardIDdup = 1;
forwardIDdupError = 1;
//closesocket(socketArray[p].s_socket);
//socketArray[p].isOk = 0;
}
else{
checkUseridDul = 0;
}
}
else{
checkUseridDul = 0;
}
}
else{
break;
}
}
}
if (string(getpost) == "POST" && forwardIDdupError != 1){
if (checkUseridDul != 1){
int len = recvStr.find("\r\n\r\n");
string messBody;
messBody = recvStr.substr(len + 4, recvStr.length() - len);
forwardRegisSuccess = 1;
string username;
string userpassword;
string userpasswordagain;
string secondname;
string sex;
string select_address;
string telephoneNum;
string email;
string department;
//username=123&userpassword=123&userpasswordagain=123&secondname=123&sex=male&select_address=beijing&telephoneNum=1234&email=123&department=xiaoshou&submitRegister=%CC%E1%BD%BB
char messageBody[1024] = { 0 };
strcpy_s(messageBody, sizeof(messageBody), messBody.c_str());
int j = 0;
char temp[100] = { 0 };
char tempstr[100] = { 0 };
string tempStr = "";
//解析每个字段
for (int i = 0; i < strlen(messageBody); i++){
//memset(messageBody, 0, sizeof(messageBody));
//memset(tempstr, 0, sizeof(tempstr));
tempStr = "";
if (messageBody[i] != '='){
temp[j] = messageBody[i];
j++;
}
else{
tempStr = string(temp);
if (tempStr == "username"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
username = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "userpassword"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
userpassword = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "userpasswordagain"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
userpasswordagain = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "secondname"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
secondname = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "sex"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
sex = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "select_address"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
select_address = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "telephoneNum"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
telephoneNum = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "email"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
email = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "department"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
department = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
}
}//for over
if (username.length() == 0 || userpassword.length() == 0 || userpasswordagain.length() == 0 || secondname.length() == 0 || sex.length() == 0 || select_address.length() == 0 || telephoneNum.length() == 0 || email.length() == 0 || department.length() == 0){
forwardRegisSuccess=0;
break;
}
//insert db
//char uportid[20] = { 0 };
//strcpy_s(temptotal,tempTotal.c_str());
//_itoa_s(socketArray[p].uPort, uportid, sizeof(uportid), 10);
char connectpresql[128];
sprintf_s(connectpresql, "dbname=postgres user=postgres password=123456");
PGconn *pcon;
pcon = PQconnectdb(connectpresql);
PGresult *res;
if (PQstatus(pcon) != CONNECTION_OK){
cout << "insert db:connect to db fail!" << endl;
}
//提取时间 timenow
SYSTEMTIME time;
GetLocalTime(&time);
char timenow[50] = { 0 };
sprintf_s(timenow, sizeof(timenow), "%d-%d-%d %d:%d:%d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
char tempstrDB[4096] = { 0 };
PQsetClientEncoding(pcon, "GBK");
sprintf_s(tempstrDB, sizeof(tempstrDB), "insert into userinfo(username, userpassword, userpasswordagain, secondname, sex,select_address, tel, email, department,registime) values('%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s')", username.c_str(), userpassword.c_str(), userpasswordagain.c_str(), secondname.c_str(), sex.c_str(), select_address.c_str(), telephoneNum.c_str(), email.c_str(), department.c_str(), timenow);
//sprintf_s(tempstrDB, sizeof(tempstrDB),"insert into userinfo(username, userpassword, userpasswordagain,secondname) values('%s', '%s', '%s','%s')", username.c_str(), userpassword.c_str(), userpasswordagain.c_str(),secondname.c_str());
//pg_char_to_encoding("utf-8");
res = PQexec(pcon, tempstrDB);
char * k = PQcmdTuples(res);
if (*k < 1){
cout << "insert DB:insert userinfo fail!" << PQerrorMessage(pcon) << endl;
PQfinish(pcon);
PQclear(res);
}
else{
cout << "insert DB:insert userinfo successfully!insert num:" << *k;
PQfinish(pcon);
PQclear(res);
}
}
}
}//处理注册结束
//处理登录开始
if (loginSystem > 0){
string recvStr = string(recvBuff);
int len = recvStr.find("\r\n\r\n");
string messBody;
messBody = recvStr.substr(len + 4, recvStr.length() - len);//取出消息体
string username;
string userpassword;
char messageBody[1024] = { 0 };
strcpy_s(messageBody, sizeof(messageBody), messBody.c_str());
int j = 0;
char temp[100] = { 0 };
char tempstr[100] = { 0 };
string tempStr = "";
//解析每个字段
for (int i = 0; i < strlen(messageBody); i++){
//memset(messageBody, 0, sizeof(messageBody));
//memset(tempstr, 0, sizeof(tempstr));
tempStr = "";
if (messageBody[i] != '='){
temp[j] = messageBody[i];
j++;
}
else{
tempStr = string(temp);
if (tempStr == "username"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
username = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "userpassword"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
userpassword = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
}
}//for over
if (username.length() > 0 && userpassword.length() > 0){
//db verify
char connectpresql[128];
sprintf_s(connectpresql, "dbname=postgres user=postgres password=123456");
PGconn *pcon;
pcon = PQconnectdb(connectpresql);
PGresult *res;
if (PQstatus(pcon) != CONNECTION_OK){
cout << "insert db:connect to db fail!" << endl;
}
//提取时间 timenow
SYSTEMTIME time;
GetLocalTime(&time);
char timenow[50] = { 0 };
sprintf_s(timenow, sizeof(timenow), "%d-%d-%d %d:%d:%d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
char tempstrDB[1024] = { 0 };
PQsetClientEncoding(pcon, "GBK");
sprintf_s(tempstrDB, sizeof(tempstrDB), "SELECT username,userpassword FROM userinfo where username = '%s'", username.c_str());
res = PQexec(pcon, tempstrDB);
char * k = PQcmdTuples(res);
char * u_name;
char * u_pass;
if (PQresultStatus(res) == PGRES_TUPLES_OK&&PQntuples(res) > 0){
//int tuples = PQntuples(res);//行数
//int fields = PQnfields(res);//每行的列数
u_name = PQgetvalue(res, 0, 0);
u_pass = PQgetvalue(res, 0, 1);
//for (int i = 0; i < tuples; i++){
//for (int j = 0; j < fields; j++){
//char *test = PQgetvalue(res, i, j);
//}
//}
}
if (u_name == username&&u_pass == userpassword){
clientID = username;
forwardLoginSuc = 1;
}
else{
forwardLoginfail = 1;
}
}
else if(username.length()==0 ||userpassword.length()==0){
break;
}
}
//处理登录结束
//处理发文章开始
if (forwardSubmitActicle == 1){
//如果已经登录
if (clientID != ""){
forwardSubmitActicle = NULL;
string recvStr = string(recvBuff);
int len = recvStr.find("\r\n\r\n");
string messBody;
messBody = recvStr.substr(len + 4, recvStr.length() - len);
forwardArticleSuccess = 1;
string articleLX;
string titleName;
string articleContent;
char messageBody[4096] = { 0 };
strcpy_s(messageBody, sizeof(messageBody), messBody.c_str());
int j = 0;
char temp[100] = { 0 };
char tempstr[4096] = { 0 };
string tempStr = "";
//解析每个字段
for (int i = 0; i < strlen(messageBody); i++){
tempStr = "";
if (messageBody[i] != '='){
temp[j] = messageBody[i];
j++;
}
else{
tempStr = string(temp);
if (tempStr == "articleLX"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
articleLX = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "titleName"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
titleName = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
if (tempStr == "articleContent"){
tempStr = "";
int m = 0;
for (int k = i + 1; k < strlen(messageBody); k++){
if (messageBody[k] != '\r'){
tempstr[m] = messageBody[k];
m++;
}
else{
tempStr = string(tempstr);
articleContent = tempStr;
i = k + 1;
memset(temp, 0, sizeof(temp));
memset(tempstr, 0, sizeof(tempstr));
j = 0;
break;
}
}
}
}
}//for over
if (articleLX.length() == 0 || titleName.length() == 0 || articleContent.length() == 0||articleLX=="xuanze"){
forwardArticleSuccess = 0;
break;
}
//insert db
char connectpresql[128];
sprintf_s(connectpresql, "dbname=postgres user=postgres password=123456");
PGconn *pcon;
pcon = PQconnectdb(connectpresql);
PGresult *res;
if (PQstatus(pcon) != CONNECTION_OK){
cout << "insert db:connect to db fail!" << endl;
}
//提取时间 timenow
SYSTEMTIME time;
GetLocalTime(&time);
char timenow[50] = { 0 };
sprintf_s(timenow, sizeof(timenow), "%d-%d-%d %d:%d:%d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
char tempstrDB[4096] = { 0 };
PQsetClientEncoding(pcon, "GBK");
sprintf_s(tempstrDB, sizeof(tempstrDB), "INSERT INTO articleinfo(username, articlelx, articlename, submitnr, submittime) values('%s', '%s', '%s', '%s', '%s')", clientID.c_str(), articleLX.c_str(), titleName.c_str(), articleContent.c_str(), timenow);
res = PQexec(pcon, tempstrDB);
char * k = PQcmdTuples(res);
if (*k < 1){
cout << "insert DB:insert userinfo fail!" << PQerrorMessage(pcon) << endl;
PQfinish(pcon);
PQclear(res);
}
else{
cout << "insert DB:insert userinfo successfully!insert num:" << *k;
PQfinish(pcon);
PQclear(res);
}
}
//没有登录,提示要先登录
else{
forwardasktoLogin = 1;
}
}
//处理发文章结束
}
}
if (FD_ISSET(socketArray[p].s_socket, &writeSet)){
/*读取文件和全局string变量展示留言方式
//如果界面上点击的是showMessage按钮
if (forwardshow == 1){
memset(CustomHtml, 0, sizeof(CustomHtml));
ifstream infile("showMessage.jsp", ios::in | ios::_Nocreate);
//ifstream infile("testJsp.jsp", ios::in | ios::_Nocreate);
if (!infile){
cout << "open showMessage.jsp fail,the error code:" << GetLastError() << endl;
continue;
}
infile.read(CustomHtml, sizeof(CustomHtml));
if (strlen(CustomHtml) <= 0){
cout << "read showMessage.jsp fail" << endl;
continue;
}
string findvalue = string(CustomHtml);
int showValue = findvalue.find("messageShow");
//找插入的位置
if (showValue > 0){
string str1 = findvalue.substr(0, showValue + 13);
str1 += showStr;
str1 += "";
//str1 += "location.reload(true);< / script>\" / > ";
str1+="