Pages: [1]   Go Down
Author Topic: TCP/IP client says CONNECTION REFUSED!  (Read 1654 times)
0 Members and 1 Guest are viewing this topic.
ਪੰਜਾਬ
Offline Offline
Edison Member
*
Karma: 12
Posts: 1573
Another year! Alone! :(
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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 "198.168.1.214:8888 connection refused" , Do not know why?
Any encryption is there which I'm not able to detect and code for?

Android Code:
Code:
/*
 * 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. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        //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"
   
    //Eventlisteners
    buttonConnect.setOnClickListener(buttonConnectOnClickListener);
    seekBar.setOnSeekBarChangeListener(seekbarchangedListener);
    }
   
    // ----------------------- SEEKBAR EVENTLISTENER - begin ----------------------------
    SeekBar.OnSeekBarChangeListener seekbarchangedListener = new SeekBar.OnSeekBarChangeListener(){
    //Methd is fired everytime the seekbar is changed
    @Override
     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"
    dataOutputStream.writeBytes("set:"+valueOfseekbar+'\n');
    }catch (UnknownHostException e) {//catch and
    outputText(e.getMessage());//display errors
} catch (IOException e) {//catch and
outputText(e.getMessage());//display errors
}
    }
     }

     @Override
     public void onStartTrackingTouch(SeekBar seekBar) {
     }

     @Override
     public void onStopTrackingTouch(SeekBar seekBar) {
     }
    };
    // ----------------------- SEEKBAR EVENTLISTENER - end ----------------------------
   
    // ----------------------- CONNECTION BUTTON EVENTLISTENER - begin ----------------------------
    Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener(){
@Override
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("192.168.1.214", 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
  changeConnectionStatus(false);
} catch (IOException e) {//catch and
outputText(e.getMessage());//display errors
changeConnectionStatus(false);
}
}else{
outputText("disconnecting from Server...");
try {//try to close the socket
  socket.close();
  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
}else{
buttonConnect.setText("connect");//change Buttontext
}
}

//Method appends text to the textfield and adds a newline character
public void outputText(String msg) {
textlog.append(msg+"\n");
}

}

Arduino Ethernet code:

Code:
#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
  Serial.begin(9600);
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  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
    delay(1);
    // close the connection:
    client.stop();
  }
}

int convertToInt(String value){
  char buf[value.length()];
  value.toCharArray(buf,value.length());
  return atoi(buf);
}
Logged

"Real Men can Accomplish  Anything"
-  Website  
- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੂਂ !

Switzerland
Offline Offline
Faraday Member
**
Karma: 108
Posts: 5144
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 192.168.1.214 8888

Do you also get a "connection refused" message?
Logged

ਪੰਜਾਬ
Offline Offline
Edison Member
*
Karma: 12
Posts: 1573
Another year! Alone! :(
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

"Real Men can Accomplish  Anything"
-  Website  
- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੂਂ !

ਪੰਜਾਬ
Offline Offline
Edison Member
*
Karma: 12
Posts: 1573
Another year! Alone! :(
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
telnet 192.168.1.214 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.
« Last Edit: September 27, 2012, 03:21:13 am by NI$HANT » Logged

"Real Men can Accomplish  Anything"
-  Website  
- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੂਂ !

Gosport, UK
Offline Offline
Faraday Member
**
Karma: 21
Posts: 3113
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
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.
Logged

ਪੰਜਾਬ
Offline Offline
Edison Member
*
Karma: 12
Posts: 1573
Another year! Alone! :(
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I have a windows 7, so I should install the Telnet client? write?
Logged

"Real Men can Accomplish  Anything"
-  Website  
- skype : nishants5  

ਫ਼ਤੇਹ ਕਰੂਂ !

Gosport, UK
Offline Offline
Faraday Member
**
Karma: 21
Posts: 3113
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#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");
                    client.println();
                    // send web page
                    client.println("<!DOCTYPE html>");
                    client.println("<html>");
                    client.println("<head>");
                    client.println("<title>Arduino Web Page</title>");
                    client.println("</head>");
                    client.println("<body>");
                    client.println("<h1>Hello from Arduino!</h1>");
                    client.println("<p>A web page from the Arduino server</p>");
                    client.println("</body>");
                    client.println("</html>");
                    break;
                }
                // 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
Logged

Miramar Beach, Florida
Offline Offline
Faraday Member
**
Karma: 138
Posts: 5846
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It could be these two lines.
Code:
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 192.168.0.1 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:
http://192.168.0.1:8888

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.
« Last Edit: June 25, 2014, 06:52:39 am by SurferTim » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks for answering SurferTim  smiley

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.
Logged

Miramar Beach, Florida
Offline Offline
Faraday Member
**
Karma: 138
Posts: 5846
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
« Last Edit: June 25, 2014, 09:24:16 am by SurferTim » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

My config seems good.

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

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

from 192.168.1.13, 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 192.168.1.11, in TCP protocol:
ddi_tcp-1 > ndm-server [RST] Seq=1 Win=0 Len=0
Logged

Miramar Beach, Florida
Offline Offline
Faraday Member
**
Karma: 138
Posts: 5846
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I tried with three different computers on XP. They all have Ethernet and serial ports (Not sure  I understand your question   smiley-confuse)
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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  smiley

Let's build a website now!

Logged

Pages: [1]   Go Up
Jump to: