免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2459 | 回复: 2
打印 上一主题 下一主题

linux下的socket是一直保持着链接的么? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-04-14 17:02 |只看该作者 |倒序浏览
我的代码如下,写的一个简单的访问telnet服务器的代码
使用socket在windows下的运行良好
我使用该框架,修改了一下,可在recv的时候
总是返回0或者-1
不知道怎么回事,是不是我对linux下的socket编程模式使用的不对



extern boost::thread g_tNionClient;
extern int g_socketNionClient;
extern bool g_bNionClientConnected;

extern string g_strNionServerIP;
extern long g_lNionPort;

extern string g_strNionClientUserName;
extern string g_strNionClientPassWord;

extern string g_strNionAirportName ;
extern long g_lNionReconnectTime;
extern long g_lNionSockTimeOut;

bool StartHYENionClient()
{
        WriteFileLogInfo_Nion("create RunHYENionClient_THREAD ....\t");
        g_tNionClient = boost::thread( &Thread_RunHYENionClient );  
               
        WriteFileLogInfo_Nion("OK");

        return true;
}


//这里是boost的一个线程,该线程持续从服务器recv数据
int Thread_RunHYENionClient()
{
        bool bFirst = true;
        while(1)
        {
                if (!bFirst)
                {
                        WriteFileLogInfo_Nion("NION Client: NION Server closed ,just reconnect after 2 sec..");
                        boost::this_thread::sleep(boost::posix_time::seconds(2));
                        bFirst = false;
                }
                if (!g_bNionClientConnected)
                {
                        shutdown(g_socketNionClient,SHUT_RDWR);
                        close(g_socketNionClient);
                        CreatesocketConnect();
                        bFirst = false;
                }

                string strBuffer;
                //string strDaqing = "statusIs running \"DaQingAirport\" ";
                string strDaqing = "statusIs running \"";
                strDaqing += g_strNionAirportName;
                strDaqing += "\" ";

                while(g_bNionClientConnected )
                {
                        char temp;
                        int ret;
                        ret = recv(g_socketNionClient,&temp,1,0);
                        if (ret == 0)        //服务器将socket关闭               
                        {
                                close(g_socketNionClient);
                                g_bNionClientConnected = false;

                                string strlog;
                                strlog = "NION Client:***** socket client closed gracefully ,remove this socket";
                                string str;
                                strlog += Inter2String(str,g_socketNionClient);
                                WriteFileLogInfo_Nion(strlog.c_str());
                                break;
                        }
                        else if (ret == -1)//出现错误,需要重连
                        {
                                g_bNionClientConnected = false;               
                                close(g_socketNionClient);
                                string strlog = "NION Client: recv error! remove this socket";
                                WriteFileLogInfo_Nion(strlog.c_str());                               
                                break;;
                        }
                        else//接收的正确数据
                        {
                                cout<<temp;
                                if (temp != '\n')
                                {
                                        strBuffer += temp;
                                }
                                else
                                {                                       
                                        if (strBuffer.find(strDaqing) >= 0)
                                        {
                                                ClearNionServerChannel();//;connect to nion and clear nion
                                        }
                                        strBuffer = "";                                       
                                }               
                        }
                        continue;
                }
        }

        return 1;
}

bool ClearNionServerChannel()
{
        /*
        //for debug
        string strDelete = "delete from npu_queue";
        Operate_NO_Log_DBBySQL(strDelete);

        string strSQL = "select * from "+g_strAREAINFO+" where QROW_ID is not null and TERM='"+g_strTerm+"'";
        try
        {
                _variant_t RecordsAffected;
                _RecordsetPtr pRecord = NULL;
                pRecord = g_Connection->Execute((LPCSTR)strSQL,&RecordsAffected,adCmdText);

                if (!pRecord->BOF)
                {
                        pRecord->MoveFirst();
                }
                else
                {               
                        if(pRecord != NULL)
                        {                               
                                if(pRecord->State)
                                {
                                        pRecord->Close();
                                }
                                pRecord = NULL;
                        }
                        return false;                               
                }
                int iComIndex = 0;
                while(!pRecord->adoEOF)
                {
                        string strAreaID = GetDBValueByFieldName("AREAID", pRecord);
                        string strTerm = GetDBValueByFieldName("TERM", pRecord);
                       
                        SendCommannd2NionServer(strAreaID, "0");
                        string strSQLUpdate;
                        strSQLUpdate= "update "+g_strAREAINFO+" set begin=null,pri=null,QROW_ID=null where areaid='"+strAreaID+"' and TERM='"+g_strTerm+"'";
                        Operate_NO_Log_DBBySQL(strSQLUpdate);

                        pRecord->MoveNext();
                }
                return true;
        }
        catch(_com_error *e)
        {
                char error[256];
                wsprintf(error,"%s",e->ErrorMessage());
                DebugMessageBox(error);

                return false;
        }
        catch (...)
        {
                //WriteSYSCatchLog(strSQL);
                return false;
        }

        */
        return false;

}


bool CreatesocketConnect()
{
connectagain:       
        if ((g_socketNionClient = socket(AF_INET,SOCK_STREAM,0)) == -1)
        {
                return false;
        }

        struct sockaddr_in Remote;
        bzero(&Remote, sizeof(Remote));
        Remote.sin_family = AF_INET;
        Remote.sin_port = htons((u_short)g_lNionPort);
        Remote.sin_addr.s_addr = inet_addr(g_strNionServerIP.c_str());
        //inet_pton(AF_INET, g_strNionServerIP.c_str(), &Remote.sin_addr);
       
        int ret = connect(g_socketNionClient,(struct sockaddr*)&Remote,sizeof(Remote));
        if(ret == -1)
        {
                WriteFileLogInfo_Nion("NION client: TRYING TO RECONNECT TO NION Server...");
                boost::this_thread::sleep(boost::posix_time::seconds(g_lNionReconnectTime));
                goto connectagain;
        }       

        if(!LoginServer(g_strNionClientUserName, g_strNionClientPassWord))
        {
                WriteFileLogInfo_Nion("NION client: login on the NION server failured!");
                close(g_socketNionClient);
                g_bNionClientConnected = false;
                goto connectagain;
        }

        struct timeval timeout = {g_lNionSockTimeOut+10,0};
        cout<<setsockopt(g_socketNionClient, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
        cout<<setsockopt(g_socketNionClient, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));

        WriteFileLogInfo_Nion("NION Client: Connect to the NION server successfully!");
        g_bNionClientConnected = true;
        return true;
}


bool LoginServer(const string& user,const string& password)
{
        char connStr[256];

        strcpy(connStr, user.c_str());
        strcat(connStr, "\r");
        strcat(connStr, password.c_str());
        strcat(connStr, "\r\n");

        if (g_socketNionClient < 0)
        {
                return false;
        }

        int sendFlag = send(g_socketNionClient,connStr, strlen(connStr), MSG_DONTROUTE);
        if(sendFlag == -1)
        {
                WriteFileLogInfo_Nion("NION Client: Send user and pass error");
                return false;
        }

        return true;
}


bool SendCommannd(const string& strMess)
{
        if (strMess.size() <= 0 || g_socketNionClient ==-1)
        {
                WriteFileLogInfo_Nion("NION Client: strMess.size() <= 0 || g_socketNionClient == 0");
                return false;
        }

        int sendFlag = send(g_socketNionClient,strMess.c_str(), strMess.size(), MSG_DONTROUTE);
        if(sendFlag == -1)
        {
                string strLog = "NION Clinet:SendCommannd  error! [";
                strLog += strMess;
                strLog += "]";
                WriteFileLogInfo_Nion(strLog.c_str());
                return false;
        }
        return true;               
}

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:56:11
2 [报告]
发表于 2011-04-14 18:30 |只看该作者
看你是如何寫代碼的了。

论坛徽章:
1
白羊座
日期:2014-01-14 17:31:01
3 [报告]
发表于 2011-04-14 18:41 |只看该作者
没看到断开的代码啊,那就是一直连着撒
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP