1. Home
    1. Dashboard
    2. Search
  2. Forum
    1. Unresolved Threads
    2. Members
      1. Recent Activities
      2. Users Online
      3. Team Members
      4. Search Members
      5. Trophys
  3. Articles
  4. Blog
  5. Videos
  6. Jobs
  7. Shop
    1. Orders
  • Login or register
  • Search
This Thread
  • Everywhere
  • This Thread
  • This Forum
  • Articles
  • Pages
  • Forum
  • Blog Articles
  • Products
  • More Options
  1. Robotforum - Support and discussion community for industrial robots and cobots
  2. Forum
  3. Cobot Help and Discussion Center
  4. KUKA LBR IIWA
Your browser does not support videos RoboDK Software for simulation and programming
Visit our Mainsponsor
IRBCAM
Robotics Channel
Robotics Training
Advertise in robotics
Sponsored Ads

Background Task TCP/IP will not reconnect after synchronization

  • JM212
  • December 9, 2020 at 2:19 AM
  • Thread is Unresolved
  • JM212
    Reactions Received
    1
    Trophies
    2
    Posts
    43
    • December 9, 2020 at 2:19 AM
    • #1

    I have written up a TCP/IP Background Task. The robot is acting as the server and I am trying to constantly listen to incoming clients. I am currently getting an error every time I synchronise the robot with the Kuka Sunrise Workbench. The error seems to be that when I reconnect I am unable to as the Socket is already Bound. This obviously means I am not closing the socket. But I am not too sure how to close the socket on an abrupt termination of the TCP/IP background task, especially when I hit the task to stop or when I go to synchronise.

    Is there a way that I could attempt to close the socket before the background task is shutoff? OTherwise I have to power cycle after everytime I synchronise.

    Java
    package application;
    
    
    import javax.inject.Inject;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.concurrent.TimeUnit;
    
    
    import com.kuka.roboticsAPI.applicationModel.tasks.CycleBehavior;
    import com.kuka.roboticsAPI.applicationModel.tasks.RoboticsAPICyclicBackgroundTask;
    
    /**
     * Implementation of a cyclic background task.
     * <p>
     * It provides the {@link RoboticsAPICyclicBackgroundTask#runCyclic} method 
     * which will be called cyclically with the specified period.<br>
     * Cycle period and initial delay can be set by calling 
     * {@link RoboticsAPICyclicBackgroundTask#initializeCyclic} method in the 
     * {@link RoboticsAPIBackgroundTask#initialize()} method of the inheriting 
     * class.<br>
     * The cyclic background task can be terminated via 
     * {@link RoboticsAPICyclicBackgroundTask#getCyclicFuture()#cancel()} method or 
     * stopping of the task.
     * @see UseRoboticsAPIContext
     * 
     */
    public class TCPServer extends RoboticsAPICyclicBackgroundTask {
        @Inject
        
          Socket Server;
          byte[] RXRawData = new byte[1024];
          private static String RXString = new String();
          ServerSocket serversocket;
            String delims = "[<>]+";     
            String tcpconnection = "CLOSED";
            private static boolean ServerConnected = false;
            private static boolean MessageReceived = false;
            private static boolean ApplicationClosed = false;
            private static String Test;
            @Inject
    
        @Override
        public void initialize() {
    
            try {
    
                serversocket = new ServerSocket(30001);    
                Server = serversocket.accept(); 
                } catch (IOException e) {
                    e.printStackTrace();
                }
            initializeCyclic(0, 500, TimeUnit.MILLISECONDS,
                    CycleBehavior.BestEffort);
        }
    
        @Override
        public void runCyclic() {
    
            // your task execution starts here
            try
            {
                if(ApplicationClosed == true)
                {
                    ApplicationClosed = false;
                }
                
                
                if(Server.isClosed())
                {
                    serversocket.close();
                    serversocket = new ServerSocket(30001);    
                    Server = serversocket.accept(); //Block Function, waits till it finds a client\
                    ServerConnected = true;
                }
                else
                    ServerConnected = false;
              
              
                InputStream input = Server.getInputStream();
                DataInputStream in = new DataInputStream(input);
                MessageReceived = false;
                in.read(RXRawData);
                MessageReceived = true;
                  
                  
                String RXRawString = new String(RXRawData);
                RXString = RXRawString.trim();
                //ServerTransfer_("What happend??");
                ServerTransfer_("/<MSGRCD><Test1><Test2><Test3><Test4><Test5><Test6>");
                String[] tokens = RXString.split(delims,0);
                  
                  
                if(tcpconnection.matches(tokens[1]) /*|| SignalTower.getApplicationState()*/)
                {
                    ServerSocketClose_();
                    ServerConnected = false;
                    ApplicationClosed = true;
                }
                try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
                } catch(IOException e) {
                try 
                {
                    serversocket.close();
                    serversocket = new ServerSocket(30001);                
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                      e.printStackTrace();
                }
        }
    
    
        //Will call this function in Robot Code when we want to send a message to the PC
        public boolean ServerTransfer_(String message)
        {
          OutputStream output;
        try {
            output = Server.getOutputStream();
            DataOutputStream out = new DataOutputStream(output);
            out.writeBytes(message);
            message = null;
            } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
            //Test = e.getMessage();
            }
        return true;
        }
        public static String getRXString()
        {
            return RXString;
        }
        public static boolean getRobotConnected()
        {
            return ServerConnected;
        }
        public static boolean getMessageReceived()
        {
            return MessageReceived;
        }
        public static boolean getApplicationClosed()
        {
            return ApplicationClosed;
        }
        //Will call this function when PC sends message wanting to close connection
        public void ServerSocketClose_()
        {
          try {
            Server.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
    }
    Display More

    This is my first time writing TCPIP. So I probably havent written it in the most ideal way either. But like I said Im trying to close the serverSocket before it is synchronised. I am not too familar with how a cyclic background task comes to an end or if there is a procedure/function I need to write that is called before it is abruptly closed.

  • panic mode
    Reactions Received
    1,278
    Trophies
    11
    Posts
    13,079
    • December 9, 2020 at 6:19 PM
    • #2

    why not make robot a client? then you don't have this issue (and some others)

    1) read pinned topic: READ FIRST...

    2) if you have an issue with robot, post question in the correct forum section... do NOT contact me directly

    3) read 1 and 2

  • Seulki
    Reactions Received
    8
    Trophies
    3
    Posts
    84
    • December 10, 2020 at 5:21 AM
    • #3

    You could try override dispose() method in your backgroundTask.

    Code
        @Override
        public void dispose() {
            ServerSocketClose_();
            
            super.dispose();    // not so sure this is needed. just my habit.
        }

    And this dispose() method will be called when you press the stop button of the backgroundTask on HMI.

    - you could do it by manually pressing this stop button, or other way to directly call dispose() when you need. ("END" packet from a client or so)

    However, You still need to stop-call dispose()- it before synchronizing.

    I experienced a bug-ish reaction when I try synchronize project without manually stopping a background task.

    It seems the instance is not properly disposed if it the dispose() method hasn't been explicitly called.

Advertising from our partners

IRBCAM
Robotics Channel
Robotics Training
Advertise in robotics
Advertise in Robotics
Advertise in Robotics

Job Postings

  • Anyware Robotics is hiring!

    yzhou377 February 23, 2025 at 4:54 AM
  • How to see your Job Posting (search or recruit) here in Robot-Forum.com

    Werner Hampel November 18, 2021 at 3:44 PM
Your browser does not support videos RoboDK Software for simulation and programming

Tag Cloud

  • abb
  • Backup
  • calibration
  • Communication
  • CRX
  • DCS
  • dx100
  • dx200
  • error
  • Ethernet
  • Ethernet IP
  • external axis
  • Fanuc
  • help
  • hmi
  • I/O
  • irc5
  • IRVIsion
  • karel
  • kawasaki
  • KRC2
  • KRC4
  • KRC 4
  • KRL
  • KUKA
  • motoman
  • Offset
  • PLC
  • PROFINET
  • Program
  • Programming
  • RAPID
  • robodk
  • roboguide
  • robot
  • robotstudio
  • RSI
  • safety
  • Siemens
  • simulation
  • SPEED
  • staubli
  • tcp
  • TCP/IP
  • teach pendant
  • vision
  • Welding
  • workvisual
  • yaskawa
  • YRC1000

Thread Tag Cloud

  • abb
  • Backup
  • calibration
  • Communication
  • CRX
  • DCS
  • dx100
  • dx200
  • error
  • Ethernet
  • Ethernet IP
  • external axis
  • Fanuc
  • help
  • hmi
  • I/O
  • irc5
  • IRVIsion
  • karel
  • kawasaki
  • KRC2
  • KRC4
  • KRC 4
  • KRL
  • KUKA
  • motoman
  • Offset
  • PLC
  • PROFINET
  • Program
  • Programming
  • RAPID
  • robodk
  • roboguide
  • robot
  • robotstudio
  • RSI
  • safety
  • Siemens
  • simulation
  • SPEED
  • staubli
  • tcp
  • TCP/IP
  • teach pendant
  • vision
  • Welding
  • workvisual
  • yaskawa
  • YRC1000
  1. Privacy Policy
  2. Legal Notice
Powered by WoltLab Suite™
As a registered Member:
* You will see no Google advertising
* You can translate posts into your local language
* You can ask questions or help the community with your knowledge
* You can thank the authors for their help
* You can receive notifications of replies or new topics on request
* We do not sell your data - we promise

JOIN OUR GREAT ROBOTICS COMMUNITY.
Don’t have an account yet? Register yourself now and be a part of our community!
Register Yourself Lost Password
Robotforum - Support and discussion community for industrial robots and cobots in the WSC-Connect App on Google Play
Robotforum - Support and discussion community for industrial robots and cobots in the WSC-Connect App on the App Store
Download