65.9K
CodeProject 正在变化。 阅读更多。
Home

通过网络进行调试输出

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.20/5 (4投票s)

2006年3月8日

CPOL

1分钟阅读

viewsIcon

33574

downloadIcon

182

通过 UDP 协议发送调试输出。

引言

当需要从运行在另一台机器上的程序接收调试信息时,一种选择是通过网络发送这些信息以便在其他地方查看。为了实现这一点,我编写了一个类库,它使用UDP协议,以便在发送消息包时避免程序中断。这个库非常简单,所以我只提供类源代码文件,可以从上面的链接下载。

使用类库的步骤

  1. 将源代码文件包含到你的项目中。
  2. 在你的源代码中添加以下代码。
    #include "NetDebug.h"
    // To make things as simple as possible,
    // all functions in the CNetDebug class are declared as static
    // so you don't need to create an instance.
    
    // CNetDebug::Init() is optional.
    // If your program doesn't call WSAStartup(), call the Init() function.
    CNetDebug::Init();
    // Set destination IP and port number.
    CNetDebug::SetAddr("192.168.10.173", 12345);
    // Once set up as shown you can print messages wherever you want.
    // just as with printf
    int num1 = 100, num2=200;
    CNetDebug::Write("Checking number=%d number2=%d", num1, num2);
    // Cleanup Winsock before exiting program
    CNetDebug::Deinit();
    
  3. 在项目设置中将Ws2_32.lib添加到链接模块中。

使用宏

此外,该类包含在编译时启用和禁用调试功能的宏。要启用它,只需使用宏而不是直接使用类即可。

NET_DEBUG_INIT();
NET_DEBUG_SET_ADDR("192.168.10.173", 12345);
...
char msg[] = "Hello World!!";
NET_DEBUG(("Greeting [%s]", msg)); // Be careful, requires double parentheses.
...
NET_DEBUG_DEINIT();
你可以通过定义 "_NO_NET_DEBUG" 常量来简单地删除调试代码。

接收消息

现在你的程序将通过网络发送消息,你需要一种收集消息的方式。不用担心!这很容易通过创建一个非常简单的服务器程序来完成。我使用以下PHP代码来获取消息,因为我认为PHP比C++更容易用于此目的。

///// PHP Code Begin
<?
    $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    if (!$s) die('create error');
    $bind_ip = "192.168.10.173"; // host ip address
    $bind_port = 12345;
    if (!socket_bind($s, $bind_ip, $bind_port)) die('bind error');
    while ( true ) {
        socket_recvfrom($s, $buf, 1024, 0, $ip, $port);
        echo date("H:i:s"), " $ip -> ", $buf, "\n";
    }
    socket_close($s);
?>

© . All rights reserved.