学习C++(www.cppentry.com)已经有一段时间了,一直都是学习基础的东西,每次写的代码都比较少,没有明确的学习目标,基础还是基础,漫无边际的,基本上都是做一道或者几道算法题,连一个小小的实战都没有,也不知道自己学得怎么样了,现在终于有一个小小的实战了《C++(www.cppentry.com) 一个网络编程(www.cppentry.com)实例》。由于自己一直在做C#,只能业余时间学习C++(www.cppentry.com),都说C++(www.cppentry.com) 是那么的难,暂时还没有感觉到有多难,毕竟写代码也有两年多了。我要学习多久才能进一家做C++(www.cppentry.com)研发的公司呢
相信在不远处有一家C++(www.cppentry.com)研发公司在等着我。
这只是一个小小的实例,包括Socket编程(www.cppentry.com)、多线程、文件操作。
简单介绍:他实现了点对点聊天,一个服务器,一个客户端,主线程用来发送数据,启动一个子线程用来接收数据,服务器记录聊天内容。他只是用上了上面所说的三个技术,如果你对上面三个技术不是很熟,或许对你有点帮助,如果你很熟,既然来了希望你能指导一下我,如果你是高手希望你能指导一下我的编码问题。我太渴望写出高效简洁的代码。
废话就少说了,程序里处处都是注释,你可以选择看看我的代码,或是选择直接运行看看。
服务器代码:
-
-
- #include "stdafx.h"
- #include <windows.h>
- #include <process.h>
- #include <iostream>
- #include "FileLog.h"
- #include "time.h"
- using namespace std;
- #pragma comment(lib,"ws2_32.lib")
-
-
- typedef struct _receiveStruct
- {
- SOCKET *Socket;
- FileLog *fileLog;
- _receiveStruct(SOCKET *_socket,FileLog *_fileLog):Socket(_socket),fileLog(_fileLog){}
- } ReceiveStruct;
-
-
- string GetDate(const char *format)
- {
- time_t tm;
- struct tm *now;
- char timebuf[20];
- time(&tm);
- now=localtime(&tm);
- strftime(timebuf,sizeof(timebuf)/sizeof(char),format,now);
- return string(timebuf);
- }
-
-
- void receive(PVOID param)
- {
- ReceiveStruct* receiveStruct=(ReceiveStruct*)param;
- char buf[2048];
- int bytes;
- while(1)
- {
-
- if((bytes=recv(*receiveStruct->Socket,buf,sizeof(buf),0))==SOCKET_ERROR){
- cout<<"接收数据失败!\n";
- _endthread();
- }
- buf[bytes]='\0';
- cout<<"客户端说:"<<buf<<endl;
- receiveStruct->fileLog->Write("客户端 ").WriteLine(GetDate("%Y-%m-%d %H:%M:%S").c_str()).WriteLine(buf);
- }
- }
-
-
-
- in_addr getHostName(void)
- {
- char host_name[255];
-
- if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {
- cout<<"Error %d when getting local host name."<<WSAGetLastError();
- Sleep(3000);
- exit(-1);
- }
-
-
- struct hostent *phe = gethostbyname(host_name);
- if (phe == 0) {
- cout<<"Yow! Bad host lookup.";
- Sleep(3000);
- exit(-1);
- }
-
- struct in_addr addr;
- memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));
- return addr;
- }
-
-
-
- SOCKET StartServer(void)
- {
-
- SOCKET serverSocket;
- if((serverSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
- cout<<"创建套接字失败!";
- Sleep(3000);
- exit(-1);
- }
- short port=1986;
- struct sockaddr_in serverAddress;
-
- memset(&serverAddress,0,sizeof(sockaddr_in));
- serverAddress.sin_family=AF_INET;
- serverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
- serverAddress.sin_port = htons(port);
-
-
- if(bind(serverSocket,(sockaddr*)&serverAddress,sizeof(serverAddress))==SOCKET_ERROR){
- cout<<"套接字绑定到端口失败!端口:"<<port;
- Sleep(3000);
- exit(-1);
- }
-
-
- if(listen(serverSocket,SOMAXCONN)==SOCKET_ERROR){
- cout<<"侦听失败!";
- Sleep(3000);
- exit(-1);
- }
-
-
- struct in_addr addr = getHostName();
- cout<<"Server "<<inet_ntoa(addr)<<" : "<<port<<" is listening......"<<endl;
- return serverSocket;
- }
-
-
-
- SOCKET ReceiveConnect(SOCKET &serverSocket)
- {
- SOCKET clientSocket;
- struct sockaddr_in clientAddress;
- memset(&clientAddress,0,sizeof(clientAddress));
- int addrlen = sizeof(clientAddress);
-
-
- if((clientSocket=accept(serverSocket,(sockaddr*)&clientAddress,&addrlen))==INVALID_SOCKET){
- cout<<"接受客户端连接失败!";
- Sleep(3000);
- exit(-1);
- }
- cout<<"Accept connection from "<<inet_ntoa(clientAddress.sin_addr)<<endl;
- return clientSocket;
- }
-
-
-
- void SendMsg(SOCKET &clientSocket,FileLog &fileLog)
- {
- char buf[2048];
- while(1){
- cout<<"服务器说:";
- gets_s(buf);
- if(send(clientSocket,buf,strlen(buf),0)==SOCKET_ERROR){
- cout<<"发送数据失败!"<<endl;
- Sleep(3000);
- exit(-1);
- }
- fileLog.Write("服务器 ").WriteLine(GetDate("%Y-%m-%d %H:%M:%S").c_str()).WriteLine(buf);
- }
- }
-
-
- int main(int argc, char* argv[]){
- WSADATA wsa;
-
-
- if(WSAStartup(MAKEWORD(2,2),&wsa)!=0){
- cout<<"套接字初始化失败!";
- Sleep(3000);
- exit(-1);
- }
-
- SOCKET serverSocket=StartServer();
- SOCKET clientSocket=ReceiveConnect(serverSocket);
-
- FileLog fileLog;
- fileLog.Open(GetDate("%Y%m%d").append(".log").c_str());
-
- ReceiveStruct receiveStruct(&clientSocket,&fileLog);
- _beginthread(receive,0,&receiveStruct);
-
- SendMsg(clientSocket,fileLog);
-
- fileLog.Close();
- closesocket(clientSocket);
- closesocket(serverSocket);
-
-
- WSACleanup();
- return 0;
- }
客户端代码:
-
- #include "stdafx.h"
- #include <windows.h>
- #include <process.h>
- #include <iostream>
- using namespace std;
- #pragma comment(lib,"ws2_32.lib")
-
-
- void Receive(PVOID param)
- {
- char buf[2096];
- while(1)
- {
- SOCKET* sock=(SOCKET*)param;
- int bytes;
- if((bytes=recv(*sock,buf,sizeof(buf),0))==SOCKET_ERROR){
- printf("接收数据失败!\n");
- exit(-1);
- }
- buf[bytes]='\0';
- cout<<"服务器说:"<<buf<<endl;
- }
- }
-
-
- unsigned long GetServerIP(void)
- {
-
- char ipStr[20];
-
- memset(ipStr,0,sizeof(ipStr));
- cout<<"请输入你要链接的服务器IP:";
- cin>>ipStr;
- unsigned long ip;
- if((ip=inet_addr(ipStr))==INADDR_NONE){
- cout<<"不合法的IP地址:";
- Sleep(3000);
- exit(-1);
- }
- return ip;
- }
-
-
- void Connect(SOCKET &sock)
- {
- unsigned long ip=GetServerIP();
-
- short port=1986;
- cout<<"Connecting to "<<inet_ntoa(*(in_addr*)&ip)<<" : "<<port<<endl;
- struct sockaddr_in serverAddress;
- memset(&serverAddress,0,sizeof(sockaddr_in));
- serverAddress.sin_family=AF_INET;
- serverAddress.sin_addr.S_un.S_addr= ip;
- serverAddress.sin_port = htons(port);
-
- if(connect(sock,(sockaddr*)&serverAddress,sizeof(serverAddress))==SOCKET_ERROR){
- cout<<"建立连接失败:"<<WSAGetLastError();
- Sleep(3000);
- exit(-1);
- }
- }
-
-
- void SendMsg(SOCKET &sock)
- {
- char buf[2048];
- while(1){
-
-
- gets_s(buf);
- cout<<"我说:";
-
- if(send(sock,buf,strlen(buf),0)==SOCKET_ERROR){
- cout<<"发送数据失败!";
- exit(-1);
- }
- }
- }
-
- int main(int argc, char* argv[]){
- WSADATA wsa;
-
- if(WSAStartup(MAKEWORD(2,2),&wsa)!=0){
- cout<<"套接字初始化失败!";
- Sleep(3000);
- exit(-1);
- }
-
-
- SOCKET sock;
- if((sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
- cout<<"创建套接字失败!";
- exit(-1);
- }
-
- Connect(sock);
-
- _beginthread(Receive,0,&sock);
- SendMsg(sock);
-
-
- WSACleanup();
- return 0;
- }
文件操作代码(FileLog.h):
- #include "iostream"
- #include "string.h"
- #include <windows.h>
- using namespace std;
-
- class FileLog
- {
- private:
- CRITICAL_SECTION cs;
- HANDLE fileHandle;
- void Lock()
- {
- EnterCriticalSection(&cs);
- }
-
- void UnLock()
- {
- LeaveCriticalSection(&cs);
- }
-
- public:
- FileLog()
- {
- InitializeCriticalSection(&cs);
- fileHandle=INVALID_HANDLE_VALUE;
- }
-
- ~FileLog()
- {
- if(fileHandle!=INVALID_HANDLE_VALUE)
- {
-
- CloseHandle(fileHandle);
- }
- DeleteCriticalSection(&cs);
- }
-
- BOOL Open(const char *fileName);
- FileLog& Write(const char *content);
- FileLog& WriteLine(const char *content);
- BOOL Read(char *buf,int size);
- BOOL Close();
- };
文件操作代码(FileLog.app):
- #include "stdafx.h"
- #include "FileLog.h"
-
- BOOL FileLog::Open(const char *fileName)
- {
- if(fileHandle==INVALID_HANDLE_VALUE)
- {
- fileHandle=CreateFile(fileName,GENERIC_WRITE|GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,
- OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
- if(fileHandle!=INVALID_HANDLE_VALUE)
- {
- SetFilePointer(fileHandle,0,NULL,FILE_END);
- return TRUE;
- }
- }
- return FALSE;
- }
-
-
- FileLog& FileLog::Write(const char *content)
- {
- Lock();
- if(fileHandle!=INVALID_HANDLE_VALUE)
- {
- DWORD dwSize=0;
- WriteFile(fileHandle,content,strlen(content),&dwSize,NULL);
- }
-
- UnLock();
- return *this;
- }
-
-
- FileLog& FileLog::WriteLine(const char *content)
- {
- Lock();
- if(fileHandle!=INVALID_HANDLE_VALUE)
- {
- DWORD dwSize=0;
- WriteFile(fileHandle,content,strlen(content),&dwSize,NULL);
- }
- UnLock();
- return FileLog::Write("\r\n");
- }
-
-
- BOOL FileLog::Read(char *buf,int size)
- {
- BOOL isOK=FALSE;
- Lock();
- if(fileHandle!=INVALID_HANDLE_VALUE)
- {
- DWORD dwSize=0;
- isOK=ReadFile(fileHandle,buf,size,&dwSize,NULL);
- }
- return isOK;
- }
-
-
- BOOL FileLog::Close()
- {
- BOOL isOK=FALSE;
- Lock();
- if(fileHandle!=INVALID_HANDLE_VALUE)
- {
- isOK=CloseHandle(fileHandle);
- fileHandle=INVALID_HANDLE_VALUE;
- }
- UnLock();
- return isOK;
- }
-
作者:陈太汉
博客:http://www.cnblogs.com/hlxs/
【编辑推荐】
- 原生代码卷土重来 C++(www.cppentry.com)欲东山再起
- 深入理解gtest C/C++(www.cppentry.com)单元测试经验谈
- C++(www.cppentry.com)程序运行时的异常处理
- C++(www.cppentry.com)程序员必读:让你的代码更强大
- 详解C++(www.cppentry.com)用户自定义转换过程