0

我正在编写一个 tcp/ip pc/arduino 项目。Arduino 有一个 ethernetshield 并用作客户端。PC 运行 boost 并利用 asio 库作为客户端。

当我尝试连接到服务器时,无法建立连接。服务器有一个网络适配器,其静态地址为 192.168.1.1。Arduino 的 IP 地址为 192.168.1.2。两者通过UTP电缆直接连接。两者都使用端口 5000。

对于 Arduino 代码,我使用示例程序进行测试,但这失败了。设置如下所示:

// Enter the IP address of the server you're connecting to:
IPAddress server(192,168,1,1); 

// Initialize the Ethernet client library
// with the IP address and port of the server 
// that you want to connect to (port 23 is default for telnet;
// if you're using Processing's ChatServer, use  port 10002):
EthernetClient client;

void setup() {
   // start the Ethernet connection:
   Ethernet.begin(mac, ip);
   // Open serial communications and wait for port to open:
Serial.begin(9600);
 while (!Serial) {
  ; // wait for serial port to connect. Needed for Leonardo only
}


 // give the Ethernet shield a second to initialize:
 delay(1000);
 Serial.println("connecting...");

 // if you get a connection, report back via serial:
 if (client.connect(server, 5000)) {
   Serial.println("connected");
 } 
 else {
   // if you didn't get a connection to the server:
   Serial.println("connection failed");
 }
}

PC 服务器代码也相当简单,在类构造函数中我执行以下操作:

    cout << "Setting up server" << endl;
    // Protocol and port
     boost::asio::ip::tcp::endpoint Endpoint(boost::asio::ip::tcp::v4(), 5000);

    // Create acceptor
    boost::asio::ip::tcp::acceptor Acceptor(IOService, Endpoint);

    // Create socket
    SmartSocket Sock(new boost::asio::ip::tcp::socket(IOService));

    cout << "Before accept..." << endl;

     // Waiting for client
         Acceptor.accept(*Sock);

    cout << "Server set up" << endl;

SmartSocket 是一个类型定义:

typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SmartSocket;

我启动服务器控制台打印“Before Accept”并在接受函数中等待传入客户端。但是当我运行我的 Arduino 代码时,我得到连接失败(在 ardunion 串行监视器中)。

有人知道出了什么问题吗?似乎服务器和客户端看不到对方。我也放下了防火墙,但这并没有帮助。任何评论都是有用的!

4

1 回答 1

2

服务器和客户端不通信的原因可能有很多。由于代码中的错误、阻止消息的防火墙、NIC 设置或根本未连接的设备。这比你想象的要普遍得多!

为确保您的连接正常,请尝试ping从 Ardunio 连接到 PC。

确保您的 asio PC 服务器代码正常。尝试像 HTTP 请求一样与它建立本地 TCP 连接。例如http://127.0.0.1:5000/hello,在 PC 上输入您的网络浏览器 url。这将在 localhost 上向您的服务器的端口 5000 发送一个 GET 请求,这至少应该在您的 PC 控制台上打印出“服务器设置”。

如果没有,请尝试在您的 PC 服务器代码和请求中使用端口 80(标准 TCP 端口)而不是 5000。如果这样可行,那么很可能是防火墙阻止了您的端口,或者您的 Adruino 代码中存在错误

但是,如果这不起作用,那么您需要仔细查看您的服务器代码。asio Daytime.2示例应该适合您。

还请接受@Igor 的建议并Wireshark在您的PC 上安装。它可能是免费的,但在调试网络问题时却是无价之宝。

于 2013-10-30T19:58:51.000 回答