📄 simple_demo.cpp
字号:
// simple_demo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "simple_demo.h"
#include "spSocketServer.h"
#include <conio.h>
#include <ctype.h>
#include <afxsock.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
using namespace spBase;
/*
下面是为了使用服务功能添加的代码
*/
//定义服务器名称,不同的程序必须定义不同的名称,
//相同名称的服务器不能在同一主机运行
//#define MY_SERVER_NAME "my_svr"
char MY_SERVER_NAME[80]="my_svr";
class CMyDisplay : public COutputDisplay
{//显示类
public:
CMyDisplay()
{};
~CMyDisplay(){};
public:
BOOL PutLine(ErrorLevel eLevel,LPCSTR pszOutput)
{
char szDesc[20];
GetErrorLevelString(eLevel,szDesc);
printf("%d %s %s\n",(int)eLevel,szDesc,pszOutput);
fflush(stdout);
return TRUE;
};
};
void MyCallback(CServerStatus* pS,CSocketChildThread* pC)
{//回调函数,功能:直接返回对方发送来的数据
BYTE bData[100];
int iRead;
while(1)
{//10 秒超时
int iRet = pC->m_sockComm.TestAndRecv(10,100,bData,iRead);
if(iRet ==SP_ERR_SUCCESS || iRet ==SP_ERR_NOT_FINISH)
{//有数据到达
// char szTemp[30];
// sprintf(szTemp,"Recved %d\n",iRead);
printf("Recved %d\n",iRead);
fflush(stdout);
// pC->m_pStore->m_pDisplay->PutLine(szTemp);
int iWrote=0;
pC->m_sockComm.Send(iRead,bData,iWrote);
}
else
{//网络故障,或者超时
printf("网络故障,或者超时");
break;
}
}
}
/*
代码结束
*/
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
int iPort = 9988;
if(argc == 2)
{
int iP =atoi(argv[1]);
if(iP)
iPort = iP;
}
sprintf(MY_SERVER_NAME,"my_svr_%d",iPort);
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
if(!AfxSocketInit())
{
cerr << _T("socket init error") << endl;
return 2;
}
/*
下面是程序控制代码
建立一个监听套接口在本地 9988 端口等待连接
可以使用telnet localhost 9988命令进行测试
*/
//启动服务器
GlobalOpenUniqueProcess(MY_SERVER_NAME);//保证当前只有一个实例在运行
CMyDisplay myDisplay;
CSocketGlobalDataStorage store(MY_SERVER_NAME,MyCallback,&myDisplay);//创建文件输出对象
store.OpenListenSocket(NULL,iPort);
printf("listent on Port : %d\n",iPort);
CSocketParentThread parent(&store);
store.GetServerStatus()->SetRunning();
parent.CreateNewThread(TRUE);//启动监听线程
while(1)
{
char ch;
ch = _getch();
ch = toupper( ch );
if(ch == 'E')
break;
}
printf("退出\n\n");
return nRetCode;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -