Go Down

Topic: TCP/IP client says CONNECTION REFUSED! (Read 3830 times) previous topic - next topic


I have Arduino with a rev3 ethernet shield and I'm trying to make work a servo connected to pin 3 work ,controlling it with the TCP client written on for Android and the other server on Arduino but with port 8888 the tcp client says " connection refused" , Do not know why?
Any encryption is there which I'm not able to detect and code for?

Android Code:
Code: [Select]
* Simple Android -> Arduino TCP Client
* 20.04.2012
* by Laurid Meyer
* http://www.lauridmeyer.com
package com.lauridmeyer.tests;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class SimpleAndroidTCPClientActivity extends Activity {
TextView textlog;//Log for outputs

Button buttonConnect;//(dis)connect Button
SeekBar seekBar;//Seekbar to control the Servo
TextView seekBarValue;//Textfield displaing the Value of the seekbar

Boolean connected=false;//stores the connectionstatus

DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;//the socket for the connection

/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        //connect the view and the objects
    buttonConnect = (Button)findViewById(R.id.connect);
    textlog = (TextView)findViewById(R.id.textlog);
    seekBar = (SeekBar)findViewById(R.id.seekbar);
    seekBarValue = (TextView)findViewById(R.id.seekbarvalue);
    textlog.setText("Starting Client");//log that the App launched
    changeConnectionStatus(false);//change connectionstatus to "disconnected"
    // ----------------------- SEEKBAR EVENTLISTENER - begin ----------------------------
    SeekBar.OnSeekBarChangeListener seekbarchangedListener = new SeekBar.OnSeekBarChangeListener(){
    //Methd is fired everytime the seekbar is changed
   public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    String valueOfseekbar = String.valueOf(progress);//save the value of the seekbar in a string
    seekBarValue.setText(valueOfseekbar);//update the value in the textfield
    if(connected){//if the socket is connected
    try {
    //send a string to the Arduino Server in the form of "set: -seekbarvalue- \n"
    }catch (UnknownHostException e) {//catch and
    outputText(e.getMessage());//display errors
} catch (IOException e) {//catch and
outputText(e.getMessage());//display errors

   public void onStartTrackingTouch(SeekBar seekBar) {

   public void onStopTrackingTouch(SeekBar seekBar) {
    // ----------------------- SEEKBAR EVENTLISTENER - end ----------------------------
    // ----------------------- CONNECTION BUTTON EVENTLISTENER - begin ----------------------------
    Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener(){
public void onClick(View arg0) {
if(!connected){//if not connected yet
outputText("connecting to Server");
try {//try to create a socket and outputstream
  socket = new Socket("", 8888);//create a socket
  dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
  outputText("successfully connected");//output the connection status
  changeConnectionStatus(true);//change the connection status
} catch (UnknownHostException e) {//catch and
  outputText(e.getMessage());//display errors
} catch (IOException e) {//catch and
outputText(e.getMessage());//display errors
outputText("disconnecting from Server...");
try {//try to close the socket
  outputText("successfully disconnected");
  changeConnectionStatus(false);//change the connection status
} catch (UnknownHostException e) {//catch and
  outputText(e.getMessage());//display errors
} catch (IOException e) {//catch and
  outputText(e.getMessage());//display errors
// ----------------------- CONNECTION BUTTON EVENTLISTENER - END ----------------------------

// Method changes the connection status
public void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
seekBar.setEnabled(isConnected);//enable/disable seekbar
if(isConnected){//if connection established
buttonConnect.setText("disconnect");//change Buttontext
buttonConnect.setText("connect");//change Buttontext

//Method appends text to the textfield and adds a newline character
public void outputText(String msg) {


Arduino Ethernet code:

Code: [Select]
#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>

// Enter a MAC address, IP address and Portnumber for your Server below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x78, 0xE1 };
byte ip[] = {192,168,1,214};
int serverPort=8888;
int servoPin=3;

// Initialize the Ethernet server library
// with the IP address and port you want to use
Server server(serverPort);

//Initialise the Servo Library
Servo myservo;

void setup()
  // start the serial for debugging
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  Serial.println("Server started");//debug

  myservo.attach(servoPin);  // attache the servo on the givven servoPin

void loop()
  // listen for incoming clients
  Client client = server.available();
  if (client) {
    String commandStr ="";//Connamdstring where incoming commands are stored

    while (client.connected()) {//if a client is connected
      if (client.available()) {//and available
        //reading the inputs from the client
        char c = client.read();
        commandStr+=c;//and ands them to the commands String

        if (c == '\n') {//if a newline character is sent (commandline is fully recieved)
          Serial.println("Command:"+commandStr);//output the command
          if(commandStr.indexOf("set:")==0){//if the command begins with "set:"
            String value=commandStr;//store the command into a new String
            value.replace("set:", " "); //replace the "set:" from the command string
            Serial.println("Set a Servo:"+value);//output the servo value
            myservo.write(convertToInt(value));//set the servo to the recieved value
          commandStr="";//reset the commandline String
    // give the client time to receive the data
    // close the connection:

int convertToInt(String value){
  char buf[value.length()];
  return atoi(buf);
"Real Men can Accomplish  Anything"

- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੁਂ!


Have you checked with a PC before trying the self-made Android app? Use a PC in the same net and enter the following command (command line interface, means terminal, command prompt or whatever your OS is calling it):

telnet 8888

Do you also get a "connection refused" message?


No Pylon I haven't tested stuff as you said on the PC system itself, I will do the same and get back to you.
"Real Men can Accomplish  Anything"

- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੁਂ!


Sep 27, 2012, 10:19 am Last Edit: Sep 27, 2012, 10:21 am by NI$HANT Reason: 1
telnet 8888

tried this it says telnet is not recognized as an internal or external command, operable programme or batch file

NOTE: I have a wireless router and modem , the ethernet connection from modem goes to WiFI router's back and my laptop is connected to internet via. WiFI whereas from the same back end of the D-Link router there are various ethernet slots where the ethernet shield is connected to.
"Real Men can Accomplish  Anything"

- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੁਂ!


telnet is not recognized as an internal or external command, operable programme or batch file

Windows 7? (probably 8 too, but I don't have that) If so, you can install the telnet client, that MS thoughtfully decided you wouldn't need, by going through Control Panel/Programs and Features/Turn Windows features on or off.

We've been 'upgraded' to Windows 7 at work.


I have a windows 7, so I should install the Telnet client? write?
"Real Men can Accomplish  Anything"

- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੁਂ!


I would. It's a useful tool to have available.


Hi everyone,

I think I have a similar problem. I'm trying to program a web server on a Arduino Ethernet rev3 without PoE.

(sorry for my english, I'm French  :smiley-mr-green: )

Here is my code, from an example on startingelectronics.com. As you can see, when a client connects to the board, the server send him html lines. Then if you reach the board from a web browser, you get a page with a little text.

Code: [Select]

#include <SPI.h>
#include <Ethernet.h>

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x51, 0xB5 };
IPAddress ip(192, 168, 0, 1); // IP address, may need to change depending on network
EthernetServer server(8888);  // create a server at port 80

void setup()
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients

void loop()
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    // send web page
                    client.println("<!DOCTYPE html>");
                    client.println("<title>Arduino Web Page</title>");
                    client.println("<h1>Hello from Arduino!</h1>");
                    client.println("<p>A web page from the Arduino server</p>");
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)

When I try to connect (with Chrome), it doesn't work. In the details I can see the error code: ERR_CONNECTION_REFUSED

the telnet function doesn't report "connection refused" but "connection failed". It seems that it's a similar problem than you


Jun 25, 2014, 01:32 pm Last Edit: Jun 25, 2014, 01:52 pm by SurferTim Reason: 1
It could be these two lines.
Code: [Select]
IPAddress ip(192, 168, 0, 1); // IP address, may need to change depending on network
EthernetServer server(8888);  // create a server at port 80

A majority of routers use for the router's IP. You might want to change that.

Most browsers expect the web server to be on port 80. Yours is on port 8888. You would need to use this:

edit: "Connection refused" is normally a router response, not the Arduino. If the Arduino will not respond, and you get that message instead, then it is probable the Arduino is assigned the IP that the router is already using. No duplicates allowed.


Thanks for answering SurferTim  :)

I already tried other configurations, changing ip adress, port number (80, 8000, 8888...), browser. I tried with Arduino 1.0.5-r2 and Arduino nightly, on windows XP 32bit.

I precise that I've any router, I'm on a local network, connecting the devices directly or via a hub or directly, with or without cross calbles.

In most of examples that I found, people use the Arduino Uno and an Ethernet shield, and not the Arduino Ethernet. I know that it's a similar configuration than mine but could it be the reason?  :smiley-roll:

I have no idea what can be the origin exept a library problem now.


Jun 25, 2014, 04:15 pm Last Edit: Jun 25, 2014, 04:24 pm by SurferTim Reason: 1
I can verify it is not a library problem. Most likely it is your network settings.

edit: If you do not know much about networking, run ipconfig from a command prompt on the Windows box and post the output.


My config seems good.

My computer Ip is, with subnet .
My board ip is, with default subnet .
I don't have a gateway.

With Wireshark, I get these frames 6 times when I try to connect with a browser:

from, in TCP protocol:
ndm-server > ddi-tcp-1 [SYN] Seq=0 win=65535 Len=0 MSS=1460 WS=2 SACK_PERM=1

and then from, in TCP protocol:
ddi_tcp-1 > ndm-server [RST] Seq=1 Win=0 Len=0


The Ethernet port is the only network device on the computer?


I tried with three different computers on XP. They all have Ethernet and serial ports (Not sure  I understand your question   :~)


I just downloaded the new version of Arduino Nightly. I uploaded my program and it works! I have no idea why it didn't with the official version 1.0.5-r2.

Anyway, thank you very much for your help SurferTim  :)

Let's build a website now!

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131