堕落不振功业废,勤耕不辍日月新

ardunio+esp8266与javaSocket网络通信(很ok的文章)

综合 hailen 30℃

功能https://blog.csdn.net/qq_31433525/article/details/79123197
通过ardunio向esp8266模块发送at指令,连接上wifi,然后向服务器发送tcp连接请求,之后是与服务器进行sockt通信,实现通过web服务器,更改设备的led开关。

实物连接
连接方式
esp8266连接,ardunio使用软串口RX=2,TX=3,
RX—–ardunio的TX
TX—–ardunio的RX
IO15–GND
CHP_EK—3.3V
RST—-3.3V
IO0—3.3V
IO2 —3.3V

硬件代码
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial mySerial(2, 3); // RX, TX
//发送的数据
String json=””;
//发送数据长度
int sendlength;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
}
Serial.println(“Goodnight moon!”);
mySerial.begin(115200);
delay(2000);
mySerial.print(“AT+RST
“);
delay(8000);
clearCash();
Serial.println(“rst finish”);
mySerial.print(“AT+CWMODE=3
“);
delay(5000);
clearCash();
Serial.println(“mode finish”);
mySerial.print(“AT+CWJAP=”wifiname”,”wifipassword”
“);
delay(8000);
clearCash();
Serial.println(“CWJAP finish”);
mySerial.print(“AT+CIPSTART=”TCP”,”192.168.1.144 “,8888
” );
delay(8000);
clearCash();
json =”{“id”:1,”name”:”szh”}”;
delay(300);
String text1 =”AT+CIPSEND=”;
sendlength =json.length()+2;
text1.concat(String(sendlength));
Serial.println(text1);
delay(300);
mySerial.println(text1);
delay(1000);
clearCash();
Serial.print(“Send String:”);
Serial.println(json);
mySerial.println(json);
delay(1000);
clearCash();
Serial.println(“setup end”);
}

void loop() { // run over and over
String inString=””;
boolean start =false;
mySerial.listen();
while(mySerial.available()){
char inChar = (char)mySerial.read();
Serial.write(inChar);
if(start){
if(inChar == ‘}’){
start =false;
Serial.println(“start false”);
}
if(start){
inString +=(char)inChar;
}
Serial.println(inString);
}
if(inChar == ‘{‘){
start =true;
Serial.println(“start true”);
delay(10);
}
delay(10);
}
if(inString != “”){
Serial.print(“InputString:”);
Serial.println(inString);
if(inString == “off”){
digitalWrite(7, LOW);
json =”{“state”:”off”}”;
delay(300);
sendResult();
}else if(inString == “on”){
digitalWrite(7, HIGH);
json =”{“state”:”on”}”;
delay(300);
sendResult();
}else{
json =”{“state”:”error”}”;
delay(300);
sendResult();
}
inString=””;
}
}
//清空缓存
void clearCash(){
while(mySerial.available()){
mySerial.read();
}
}
//发送结果数据
void sendResult(){
String text1 =”AT+CIPSEND=”;
sendlength =json.length()+2;
text1.concat(String(sendlength));
mySerial.println(text1);
delay(1000);
clearCash();
mySerial.println(json);
delay(1000);
clearCash();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
注:每一次发送软串口会返回结果,所以需要将这些信息读取掉。通过at指令,会不太稳定,延迟时间可以长一点。与java的通信协议为json数据,往java发数据,可以完整读取,但java发往设备会出现乱码,所以可以将数据长度简单或者重发。

javaWeb代码
web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns=”http://xmlns.jcp.org/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”
version=”3.1″>
<servlet>
<servlet-name>send</servlet-name>
<servlet-class>com.test.example.SendServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>send</servlet-name>
<url-pattern>/send.jsp</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.test.example.SocketListener</listener-class>
</listener>
</web-app>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
服务器启动运行代码

public class SocketListener implements ServletContextListener{

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
new Thread(new Runnable() {
@Override
public void run() {
new SocketServer();
}
}).start();
}

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SocketServer {
/**端口号*/
private static final int port = 8888;
/** 线程池*/
private ExecutorService mExecutorService;
/**ServerSocket对象*/
private ServerSocket mServerSocket;
/**存储socket*/
public static Map<String,Socket> socketMap =new HashMap<>();
private String ip;

public SocketServer() {
try {
System.out.println(“socket启动”);
//设置socket端口
mServerSocket = new ServerSocket(port);
//创建线程池
mExecutorService = Executors.newCachedThreadPool();
// 用来临时保存客户端连接的Socket对象
Socket client = null;
while(true){
client = mServerSocket.accept();
ip = client.getInetAddress().getHostAddress();
System.out.println(“ip=”+ip);
socketMap.put(“1″,client);
System.out.println(client+”——“);
mExecutorService.execute(convertData);
}

} catch (IOException e) {
e.printStackTrace();
}
}
/**处理数据*/
public Runnable convertData = new Runnable(){

@Override
public void run() {
System.out.println(“convertData”);
int result;
try {
Socket client = socketMap.get(“1”);
while (true) {
InputStream inputStream = client.getInputStream();
OutputStream outputStream =client.getOutputStream();
while(inputStream.available()>0) {
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
String resultData = new String(data);
resultData = replaceBlank(resultData);
System.out.println(“resultData=” + resultData);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};

/***
*去除空格,水平制表符,换行,回车
* @param str
* @return
*/
public static String replaceBlank(String str) {
String dest = “”;
if (str!=null) {
Pattern p = Pattern.compile(“\s*| |
|
“);
Matcher m = p.matcher(str);
dest = m.replaceAll(“”);
}
return dest;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
发送信息代码

public class SendServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Socket client = SocketServer.socketMap.get(“1”);
System.out.println(“client=”+client);
String send =”{off}”;
OutputStream out = client.getOutputStream();
out.write(send.getBytes());
out.flush();
System.out.println(“send finish”);
}
}
———————
作者:poorSir
来源:CSDN
原文:https://blog.csdn.net/qq_31433525/article/details/79123197
版权声明:本文为博主原创文章,转载请附上博文链接!

转载请注明:我是IT » ardunio+esp8266与javaSocket网络通信(很ok的文章)

喜欢 (0)or分享 (0)