无法将tcp数据收集到矢量openframeworks

时间:2014-08-24 00:13:16

标签: c++ tcpclient openframeworks

我试图通过ofTTCPClient来填充带有指针数据的向量字符。

指针tmpData正在接收数据,但是如果我尝试将数据推送到向量中,我会收到此错误。

即使我尝试使用char“手动”填充向量,如下所示:     tcpMainData.push_back( 'A');

我收到错误:

libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
(lldb) 

这是我的计划:

#include "ofApp.h"

using namespace std;

vector<char> tcpMainData;

//This is a temporary size variabel, until a function is made.
int tmpDataSize = 100;
char tmpData;


//--------------------------------------------------------------
void ofApp::setup(){

}

//--------------------------------------------------------------
void ofApp::update(){

    //Listen on the port for tcp data if we are connected to the server
    if (!TCPClient.isConnected()) {
        state = OFFLINE;
    }else if (TCPClient.isConnected() && state != RECEIVING) {
                state = LISTENING;
    }

    //TCP package received
    if((int)TCPClient.receiveRawBytes((char *) &tcpMainData, sizeOfTcpChunk) > 1 && state == LISTENING) {

        state = RECEIVING;
    }

    //Filling up vector with tcp data
    if (state == RECEIVING) {

        for (int i = 0; i < tmpDataSize; i++) {
            TCPClient.receiveRawBytes((char *) &tmpData, sizeOfTcpChunk);

            tcpMainData.push_back(tmpData);
        }

        state = LISTENING;
    }
}

//--------------------------------------------------------------
void ofApp::draw(){

    if (state == OFFLINE) {
        ofDrawBitmapString("Press C to connect", 50, 100);
    }
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    if (key == 'c') {
        TCPClient.setup("127.0.0.1", TCPPort);
    }
}

如果有相关内容,请提供我的标题:

...

//TCP CONF
ofxTCPClient TCPClient;
int TCPPort = 50014;

int sizeOfTcpChunk = 4;             //Size of TCP packages (Chunks)

//Program state
enum clientState {
    OFFLINE,
    LISTENING,
    RECEIVING,
};

clientState state = LISTENING;

1 个答案:

答案 0 :(得分:0)

您忽略了错误发生的位置 这里有两个错误(我已经将代码中的点放到上下文中):

vector<char> tcpMainData;
TCPClient.receiveRawBytes((char *) &tcpMainData, sizeOfTcpChunk)

你将向量转换为char *错误。它应该是

(char *) &tcpMainData[0]

我强烈怀疑你可以用这个来写tcpMainData。此演员表仅用于从矢量中读取。我的猜测是,你因此得到了错误信息。

char tmpData;
TCPClient.receiveRawBytes((char *) &tmpData, sizeOfTcpChunk);

正如Galik所提到的,tmpData是一个字节。你需要像char tmpData[100]

这样的东西

作为参考,TCPClient.receiveRawBytes函数的签名是:

int ofxTCPClient::receiveRawBytes(char *receiveBytes, int numBytes)