packagecom.example.esp8266androidclient;importjava.io.IOException;importjava.io.PrintStream;importjava.net.Socket;importandroid.os.Bundle;importandroid.support.v7.app.ActionBarActivity;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.Toast;public class ESP8266AndroidClientMainActivity extends ActionBarActivity implementsView.OnClickListener
{private EditText IP;//IP
private EditText PORT;//端口号
private String stringip;//字符串类型IP
private int stringport;//字符类型端口号
private Button connect;//连接
private Socket socket;//套接字
private PrintStream out;//打印输出流
private ConnectThread connectthread;//连接线程
private Button open;//按钮LED灯开
private Button close;//按钮LED灯关
@Overrideprotected voidonCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_esp8266_android_client_main);
connect=(Button)findViewById(R.id.button1);
open=(Button)findViewById(R.id.button2);
close=(Button)findViewById(R.id.button3);
IP=(EditText)findViewById(R.id.editextip);
PORT=(EditText)findViewById(R.id.editextport);
connect.setOnClickListener(this);
open.setOnClickListener(this);
close.setOnClickListener(this);
}
@Overridepublic voidonClick(View v)
{switch(v.getId())
{caseR.id.button1:if( socket == null || !socket.isConnected())
{
stringip=IP.getText().toString();
stringport=Integer.valueOf(PORT.getText().toString());
connectthread= newConnectThread(stringip, stringport);
connectthread.start();
}if(socket != null &&socket.isConnected())
{try{
socket.close();
socket=null; //清空mSocket
connect.setText("连接");
Toast.makeText(ESP8266AndroidClientMainActivity.this,"连接已关闭", Toast.LENGTH_LONG).show();
}catch(IOException e)
{
e.printStackTrace();
}
}break;caseR.id.button2:if(out!=null)
{
out.print("0");
out.flush();
}break;caseR.id.button3:if (out!=null)
{
out.print("1");
out.flush();
}break;
}
}private class ConnectThread extendsThread
{privateString ip;private intport;public ConnectThread(String ip,intport){this.ip=ip;this.port=port;
}
@Overridepublic voidrun()
{try{
socket=newSocket(ip,port);
out= newPrintStream(socket.getOutputStream());
runOnUiThread(newRunnable()
{
@Overridepublic voidrun()
{
connect.setText("断开");
Toast.makeText(ESP8266AndroidClientMainActivity.this,"连接成功",Toast.LENGTH_LONG).show();
}
});
}catch(IOException e)
{
e.printStackTrace();
runOnUiThread(newRunnable()
{
@Overridepublic voidrun()
{
connect.setText("断开");
Toast.makeText(ESP8266AndroidClientMainActivity.this,"连接失败",Toast.LENGTH_LONG).show();
}
});
}
}
}
}