与设置为 ESP8266-01 的服务器通信的 TCP 客户端



我正在设置Android应用程序和连接到Arduino uno的ESP8266模块之间的TCP/IP通信。我正在使用 AT 命令按如下方式设置服务器:

AT+CWMODE=1 AT+CIPMUX=1 AT+CIPSERVER=1,80


我为每个都确定。

我想向应用程序发送一个 int:0 或 1,应用程序读取 int,然后将在 editText 中键入的文本发送到ESP8266

现在,这是我的应用程序代码:

public class MainActivity extends AppCompatActivity {
TextView tv;
EditText txt;
EditText txt2;
Button b;
string response;
private static Socket s ;
private static PrintWriter printWriter;
String message="";
private static String ip="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button);
txt = (EditText) findViewById(R.id.editText);
tv = (TextView) findViewById(R.id.textView) ;
txt2=(EditText)findViewById(R.id.editText2);
}
class myTask extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... params)
{
try
{        s= new Socket(ip,80);
//READING THE INPUT
BufferedReader in = new BufferedReader(new 
InputStreamReader(s.getInputStream()));
while(in!=null) {
response = in.readLine();
}
//SENDING THE MESSAGE
printWriter= new PrintWriter(s.getOutputStream());
printWriter.write(message);
printWriter.flush();
post_send();

// closing all connections
// printWriter.close();
// in.close();
// s.close();

}catch(IOException e)
{e.printStackTrace();}
return null;
}
}
public void send_text(View v)
{
message= txt.getText().toString();
ip=txt2.getText().toString();
myTask mt = new myTask();
mt.execute();
Toast.makeText(getApplicationContext(),"MT 
LAUNCHED",Toast.LENGTH_LONG).show();
}
public void post_send(){
Toast.makeText(getApplicationContext(),response 
,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),"Data 
sent",Toast.LENGTH_LONG).show();
}
}

我有 1 个按钮来创建套接字并接收任何数据,然后发送文本。

当我单击该按钮时,我在串行监视器上收到以下消息:

0, connected 

所以我输入:

AT+CIPSEND=0,4

我得到 :

SEND OK

但没有一个祝酒词显示 帮帮我?我做错了什么?

s = new Socket(ip, 80(;

如果你在onClickListener的onClick((中执行该代码,你会得到一个NetworkOnMainThreadException。这会让你的应用崩溃。

所有互联网代码(包括连接和读取(都应该从线程或AsyncTask执行。

您的写作已经在AsyncTask中。这是要走的路。

最新更新