zoukankan      html  css  js  c++  java
  • mina服务端与c++客户端通信2

    原文地址:http://www.cppblog.com/chugf/archive/2011/07/05/150224.html

    Java与C++通讯还有编码转码的问题存在,假设通讯编码采用UTF-8

    C++客户端发送时需要转码成UTF-8编码,接收服务端应答消息后再转回Unicode或者GBK编码

    下面给出完成的C++客户端通讯示例:

    void Transcoding(LPCTSTR src, UINT srcCode, string& dest, UINT destCode)   
    {   
        int len = MultiByteToWideChar(srcCode, 0, src, -1, NULL, 0);     
        WCHAR* srcTemp = new WCHAR[len];     
        MultiByteToWideChar(srcCode, 0, src, -1, srcTemp, len);     
        len = WideCharToMultiByte(destCode, 0, srcTemp, -1, NULL, 0, NULL, NULL);     
        char* destTemp = new char[len];     
        WideCharToMultiByte(destCode, 0, srcTemp, -1, destTemp, len, NULL, NULL);     
      
        dest = destTemp;   
      
        delete []srcTemp;     
        delete []destTemp;     
    }  
      
    int _tmain(int argc, _TCHAR* argv[])  
    {  
        // client connect  
        CXSocket client;  
        client.initWinSocket();  
        client.setAddress("127.0.0.1");  
        client.setPort(1234);  
        client.setProtoType(TCP);  
        int ret = client.connect();  
        if(ret < 0)  
        {  
            getchar();  
            return 0;  
        }  
      
        // 加通讯协议头demo  
        // client send  
        char send[] = {"CXSocket 第一个测试用例."};  
      
        string utf8;  
        Transcoding(send, CP_ACP, utf8, CP_UTF8);  
      
        XNET::TPacketHeader sendHeader;  
        sendHeader.m_HeaderSig = 0xABCD;  
        swap_2(sendHeader.m_HeaderSig);  
        sendHeader.m_Length = (int)utf8.length();  
        swap_4(sendHeader.m_Length);  
      
        char buffer[1024] = {0};  
        memcpy(buffer, &sendHeader, XNET::TCP_HEADLEN);  
        memcpy(&buffer[XNET::TCP_HEADLEN], utf8.c_str(), utf8.length());  
        client.sendBuf(buffer, (int)(XNET::TCP_HEADLEN + utf8.length()));  
      
        // client recv  
        XNET::TPacketHeader recvHeader;  
        client.receiveBuf(&recvHeader, XNET::TCP_HEADLEN);  
        swap_2(recvHeader.m_HeaderSig);  
        swap_4(recvHeader.m_Length);  
        char* recv = new char[recvHeader.m_Length + 1];  
        memset(recv, 0, recvHeader.m_Length + 1);  
        client.receiveBuf(recv, recvHeader.m_Length);  
        string ansi;  
        Transcoding(recv, CP_UTF8, ansi, CP_ACP);  
      
        client.close();  
        client.uninitWinSocket();  
      
        getchar();  
      
        return 0;  
    }  


     

  • 相关阅读:
    Redis学习笔记--Redis数据过期策略详解
    网络带宽和速度测试windows和linux用iperf工具
    如何将rabbitmq集群中的某个节点移除.
    关于linux系统密码策略的设置
    linux 系统ssh超时设置
    linux安全 设置登录失败次数后,拒绝登录
    tomcat隐藏版本号
    第 16 章 模板与泛型编程
    第 15 章 面向对象程序设计
    第 14 章 重载运算与类型转换
  • 原文地址:https://www.cnblogs.com/nafio/p/9137759.html
Copyright © 2011-2022 走看看