Problems in "WiFiClient.h" of Arduino IDE for ESP8266

Hello everybody! I use WiFiClient to connect to my server by socket, but I cannot connect to the server, it seems that function WiFiClient::connected() return 0, I don’t know the correct approach to connect a server by socket, which class should I use, WiFiClient or HTTPClient or other class I don’t know?
I am sure that the address and port are correct.

Usecase: I use it to upload a String to my server to verify the user identity first, after getting the returning message from the server I would send a byte array to the server.

Here is my key code:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
WiFiClient photoClient;

int uploadPhoto(){
  byte tryTime=0;
  String returnMsg="";
  String MACAddr=WiFi.macAddress();
  MACAddr.replace(":","");
  writeSerial(("ACCESS:"+WEBSITE_SEND_PHOTO).c_str());
  photoClient.setNoDelay(true);
  photoClient.connect(WEBSITE_SEND_PHOTO,3000);
  while(!photoClient.connected()){//wait for connection success
    writeRawSerial(F("."),false);
    if((tryTime++)>=10){//try 10 times
      tryTime=0;
      writeRawSerial(F(" "),true);//writeRawSerial() and writeSerial() is defined
      writeSerial(F("<STATUS>FIRST_CONNECTION_FAIL</STATUS>"));
      writeSerial("<INFO>"+(String(photoClient.connected()))+"</INFO>");
      return -1;
    }
    delay(1000);
  }
  photoClient.write((String("<TYPE>gas</TYPE><USER_ID>"+USER_ID+"</USER_ID><MAC>"+MACAddr+"</MAC><END>")).c_str());//send verification info
  writeSerial(F("photoClient.write((String(\"<TYPE>gas</TYPE><USER_ID>\"+USER_ID+\"</USER_ID><MAC>\"+MACAddr+\"</MAC><END>\")).c_str());"));
  while(!photoClient.available()){//wait for returning message
    writeRawSerial(F("."),false);
    if((tryTime++)>=10){
      tryTime=0;
      writeRawSerial(F(" "),true);
      writeSerial(F("<STATUS>FIRST_SEND_FAIL</STATUS>"));
      return -1;
    }
    delay(200);
  }
  writeRawSerial(F(" "),true);
  while(photoClient.available()){
    returnMsg+=(char)photoClient.read();
  }
  bool returnStatus=processReturnMsg(returnMsg);
  writeHttpReturnSerial(returnMsg);
  if(returnStatus){//send array
    returnMsg="";
    writeSerial(F("<STATUS>START_SENDING</STATUS>"));
    photoClient.write(Img,imgSize);
    while(!photoClient.available()){
      writeRawSerial(F("."),false);
      if((tryTime++)>=10){
        tryTime=0;
        writeRawSerial(F(" "),true);
        writeSerial(F("<STATUS>SECOND_SEND_FAIL</STATUS>"));
        return -1;
      }
      delay(200);
    }
    writeRawSerial(F(" "),true);
    while(photoClient.available()){
      returnMsg+=(char)photoClient.read();
    }
    photoClient.stop();
    returnStatus=processReturnMsg(returnMsg);
    if(returnStatus){//succeed
      delete(Img);
      writeSerial(F("<STATUS>SEND_SUCCESS</STATUS>"));
      return 1;
    }
    else{//failed
      writeSerial(F("<STATUS>SEND_FAIL</STATUS>"));
      return 0;
    }
  }
  else{//verification error
    photoClient.stop();
    writeSerial(F("<STATUS>NONE_USER</STATUS>"));
    return 0;
  }
}

Thank you for reading my question!
:slight_smile:

port is 3000. is it enabled on firewall of the server?

Juraj:
port is 3000. is it enabled on firewall of the server?

I tested it with Java client and Android client I wrote, it can be accessed. So there will be no problem with the server.

Juraj:
port is 3000. is it enabled on firewall of the server?

I tried WiFiClient like what I posted and also HTTPClient, I just cannot access to the server with this port, both failed when using function connected() to judge connection status.

Juraj:
port is 3000. is it enabled on firewall of the server?

I don't know what's the limitation of the protocol that WiFiClient and HTTPClient support.

WiFiClient is socket: connect, write, flush, read, close. HTTPClient handles HTTP protocol over WiFiClient: get, post, parse response

Juraj:
WiFiClient is socket: connect, write, flush, read, close. HTTPClient handles HTTP protocol over WiFiClient: get, post, parse response

That's confusing...
The program just failed when I call connected(). Does WiFiClient supports all kinds of socket and port?

what is the value of WEBSITE_SEND_PHOTO?
show me your working java test code

Juraj:
what is the value of WEBSITE_SEND_PHOTO?
show me your working java test code

I translated my code to php just now, but the test client is still run on java.

Here is server code in php.

<?php
	set_time_limit ( 0 );  
	$ip = '172.18.89.152';   
	$port = 3000;
	
	if (($sock = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP )) < 0)
	{
		echo "socket_create() failed: reason: " . socket_strerror ( $sock ) . "\n";
	}
	 
	if (($ret = socket_bind ( $sock, $ip, $port )) < 0)
	{
		echo "socket_bind() failed: reason: " . socket_strerror ( $ret ) . "\n";
	}
	if (($ret = socket_listen ( $sock, 4 )) < 0)
	{ 
		echo "socket_listen() failed: reason: " . socket_strerror ( $ret ) . "\n";
	}
	 
	 
	do
	{
		if (($msgsock = socket_accept ( $sock )) < 0)
		{ 
			echo "socket_accept() failed: reason: " . socket_strerror ( $msgsock ) . "\n";
			break;
		}
		else
		{
				$buf = socket_read ( $msgsock, 8192 );   
				$return_msg='<STATUS>success</STATUS><DELAY>10</DELAY>[END]';
				socket_write ( $msgsock, $return_msg, strlen ( $return_msg ) );  
				$talkback = "Recieve buffer: $buf\n";  
				echo $talkback;
		}
		socket_close ( $msgsock );
	} while ( true );
	socket_close ( $sock );
?>

And here is the test client.

package socket_test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
	
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("172.18.89.152", 3000);
			Thread thread=new Thread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {

						PrintWriter out=new PrintWriter(socket.getOutputStream());
						try {
							out.println("New msg");
						} catch (Exception e) {
							e.printStackTrace();
						};
						out.flush();
						
						InputStream inputStream = socket.getInputStream();
						InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
						BufferedReader br = new BufferedReader(inputStreamReader);
						String msg;
							try {
								while ((msg=br.readLine())!=null) {
										System.out.println(msg);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						br.close();
						inputStreamReader.close();
						inputStream.close();
						
						out.close();
						socket.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				
			});
			thread.start();
	    }catch(Exception e){
			e.printStackTrace();
			System.out.println("Server is offline");
	    }
	}
}

and in your Arduino sketch you connect to a WiFi network in setup()? show the complete sketch

Juraj:
and in your Arduino sketch you connect to a WiFi network in setup()? show the complete sketch

test.ino (11.2 KB)

ok, but the sketch doesn't answer the question if the esp is connected to WiFi network. it is some PC program sending commands to esp over Serial?

Juraj:
ok, but the sketch doesn't answer the question if the esp is connected to WiFi network. it is some PC program sending commands to esp over Serial?

As I said, the android app sends wifi info to the arduino through HC05, then the arduino sends wifi info the ESP8266, then ESP8266 connects to the target wifi.

write a simple sketch to test the connection

Juraj:
write a simple sketch to test the connection

I found that it had connected to a wifi after testing, and the HTTPClient did work while sending a HTTP request to my server, but the socket connection didn't work.

I had the same problem on same setup. HTTPClient works but WifiClient does not.