2013-03-13 84 views
1

你好#1社區,UDP包傳送和C++

我必須努力實現使用C++ UDP傳輸時下列問題:

1)我想建立將收到一個簡單的UDP數據包的功能用類似「/ location 7 5」的字符串解析浮點值7和5並將其存儲到數組中。有沒有關於如何做到這一點的例子?

2)嘗試使用OSCPacket從https://code.google.com/p/oscpack/了幾個小時後,但我不能讓過去這裏顯示任何編譯器錯誤:http://i.tylian.net/untitloxo.png

由於錯誤信息顯示,誤差來源於OSCPack,而不是我的代碼。有沒有人熟悉這個或有沒有更好的方法來實現UDP數據包傳輸?

3)我只使用ws32.dll庫,但除此之外還有其他庫嗎?

隨時回覆部分或全部多部分問題,並讓我知道是否需要更多細節!另外,我的目標平臺是Windows 7 64位。

非常感謝您的時間!

這裏有一些我與OSCPacket完成的代碼:

包括:

#include <iostream> 
#include <cstring> 

#if defined(__BORLANDC__) // workaround for BCB4 release build intrinsics bug 
namespace std {using ::__strcmp__; } // avoid error: E2316 '__strcmp__' is not a member of 'std'. 
#endif 

#include "osc/OscReceivedElements.h" 
#include "osc/OscPacketListener.h" 
#include "ip/UdpSocket.h" 

#define PORT 7000 

分組聽者

float* coordinateFromOSC = (float*) malloc (2); 
class PacketListener : public osc::OscPacketListener { 
protected: 

    virtual void ProcessMessage(const osc::ReceivedMessage& m, 
       const IpEndpointName& remoteEndpoint) 
    { 
     (void) remoteEndpoint; // suppress unused parameter warning 

     try{ 
      //the return value, array of 2, [0] for xValue, [1] for yValue 
    //will be stored at global variable coordinateFromOSC 

    // Trying to parse the packet. osc::OsckPacketListener 
      if(strcmp(m.AddressPattern(), "/location") == 0){ 
       // Streaming input as argument 
       osc::ReceivedMessageArgumentStream args = m.ArgumentStream(); 
       float xValue, yValue; 
       args >> xValue >> yValue >> osc::EndMessage; 

      coordinateFromOSC[0] = xValue; 
      coordinateFromOSC[1] = yValue; 
      } 

     }catch(osc::Exception& e){ 
      // any parsing errors such as unexpected argument types, or 
      // missing arguments get thrown as exceptions. 
      std::cout << "Invalid format: " 
       << m.AddressPattern() << ": " << e.what() << "\n"; 
     } 
    } 
}; 

,最後在功能我需要所存儲的值

PacketListener listener; 
UdpListeningReceiveSocket s(IpEndpointName(IpEndpointName::ANY_ADDRESS, PORT), &listener); 
+0

可以發佈您的代碼嗎? – Raptor 2013-03-13 04:22:36

+0

我用我的代碼更新了原始文章,是否足夠使用? – hikousagi 2013-03-13 04:41:00

回答

0

爲了解析字符串在C++中,嘗試流運營商(旁白:就您的輸入真正需要是字符串):

std::string str("/location 7 5"); 
std::stringstream ss(str); 
std::string cmd; 
float x, y; 
ss >> cmd >> x >> y; 

對於OSCPacket,它可能是你沒有設置項目設置正確。爲什麼不使用Winsock?

有關使用Winsock的示例,請參見http://www.adp-gmbh.ch/win/misc/sockets.html

+0

我注意到這個解決方案依賴於一個無限循環來持續查找新的數據包更新。我正在編寫的程序將不斷接收數據包,會爲這種浪費資源分配一個線程? – hikousagi 2013-03-13 05:15:11

+0

我用你的winsock例子去了,雖然他們的聽衆是TCP端口......感謝這些例子! – hikousagi 2013-03-14 02:32:22

+0

@hikousagi萬一錯過了;使用UDP只需使用'SOCK_DGRAM'而不是'SOCK_STREAM'。 – congusbongus 2013-03-14 03:01:30

0

如果您目前的圖書館仍然存在問題,您可能需要查看Boost和ASIO圖書館。

此頁UDP Echo Server Example可能會幫助您入門。