我在我的arduino上安装了一个简单的以太网服务器示例。我设置了IP地址和MAC地址。我可以从PC上ping Arduino,但我无法从简单的Java程序发送任何数据。Arduino以太网盾+ Java套接字连接
下面是Arduino的源:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 172, 16, 201, 218 };
EthernetServer server = EthernetServer(8080);
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and write them back
// to any clients connected to the server:
server.write(client.read());
}
}
我可以从命令提示符下执行ping的Arduino:
C:\WINDOWS\system32>ping 172.16.201.218
Pinging 172.16.201.218 with 32 bytes of data:
Reply from 172.16.201.218: bytes=32 time<1ms TTL=128
Reply from 172.16.201.218: bytes=32 time<1ms TTL=128
Reply from 172.16.201.218: bytes=32 time<1ms TTL=128
Reply from 172.16.201.218: bytes=32 time<1ms TTL=128
Ping statistics for 172.16.201.218:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
C:\WINDOWS\system32>
的客户端Java是:
package ardsocket;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ArdSocket {
public static void main(String args[]) throws IOException {
final String host = "172.16.201.218";
final int portNumber = 8080;
System.out.println("Creating socket to '" + host + "' on port " + portNumber);
while (true) {
Socket socket = new Socket(host, portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("server says:" + br.readLine());
BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
String userInput = userInputBR.readLine();
out.println(userInput);
System.out.println("server says:" + br.readLine());
if ("exit".equalsIgnoreCase(userInput)) {
socket.close();
break;
}
}
}
}
当我运行Java源时什么也没有发生.. 另外如果我尝试通过IP连接到Telnet并且端口8080是相同的故事。
我做错了什么?
谢谢Shazin,我已经复制了你的代码,但问题仍然存在。也尝试只连接我的电脑与lan电缆到arduino。我可以ping通它,但是我无法发送或接收来自Arduino的任何数据。 – Ferguson