尝试创建到arduino服务器的套接字连接时,TCP客户端停止工作

时间:2017-10-13 08:58:27

标签: java android sockets tcp arduino

我正在尝试制作TCP服务器和TCP客户端。我使用Arduino完成了服务器。

void setup() {

 pinMode(button, INPUT);   
//Connnect to WiFi Network
Serial.begin(115200);
WiFi.begin(ssid,password);
Serial.println("");
//Wait for connection

while (WiFi.status()!=WL_CONNECTED)
{
  delay(500);
  Serial.print(".");
}
//Print status to Serial Monitor
Serial.print("connected to: "); Serial.println(ssid);
Serial.print("IP Address: "); Serial.println(WiFi.localIP());

//Start the TCP server
server.begin();
}

void loop() {

  client = server.available();
  client.setTimeout(10000);
  str=client.readStringUntil('\n');
  if(client){

   if(client.connected()){
    Serial.println("connected to client");

 if(str=="take")
 {
    // read the state of the pushbutton value:
  buttonState = digitalRead(button);

  if (buttonState == HIGH) {

    client.println("open!");
  } else {

    client.println("close");
  }
 }
 else{
   client.println("error");
 }

   client.flush();
   client.stop();

   }
  }
}

我认为服务器正在运行,因为一切都适用于netcat。 客户端部分是一个Android应用程序,我已经做了。这个概念是当我按下应用程序中的按钮时,套接字必须连接到服务器并更改EditText文本。每次程序停止时按下按钮。当我调试程序时,我得出结论,问题是创建套接字。服务器IP是192.168.1.106,端口是3030.创建套接字我错了吗?

    View.OnClickListener btns=new View.OnClickListener() {

        public void onClick(View view) {

                EditText et = (EditText) findViewById(R.id.edittext);
                String str = et.getText().toString();
                String sentence;

           // int mTimeout=10000;

            String modifiedSentence;
                BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
            try {
                //clientSocket.setSoTimeout(mTimeout);
                InetAddress ip=InetAddress.getByName("192.168.1.106");
               Socket  clientSocket = new Socket(ip,3030);

                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                sentence = inFromUser.readLine();
                outToServer.writeBytes(sentence + '\n');
                modifiedSentence = inFromServer.readLine();
                et.setText(modifiedSentence);

                clientSocket.close();
            } catch (IOException e) {
                System.out.println("Exception "+e);
            }

        }
}; 

0 个答案:

没有答案