我正在编写一个 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 串行监视器中)。
有人知道出了什么问题吗?似乎服务器和客户端看不到对方。我也放下了防火墙,但这并没有帮助。任何评论都是有用的!