title: Calling Matlab by JADE agent as multi-threading for multiple connections
body: <p>I am working on JADE (Java) project that connects Matlab by a TCP connection with client-server sockets. Here, JADE creates a server socket and Matlab creates a client socket. I am retrieving some data from Matlab to Java (JADE). The following is my code where I am calling Matlab by JADE through Agent. <strong>(1)</strong> The issue is I cannot re-run it without re-starting the program again. I believe that I require a multithread java instance with multithread Matlab instance that could connect and synchronize each other. However, I found that Matlab is a single thread. The program throws binding error.</p>
  
  <pre><code>WARNING: Error adding ICP jade.imtp.leap.JICP.JICPPeer@1dbb27d[Cannot bind server socket to localhost port 1099].
  jade.core.AgentContainerImpl joinPlatform
  SEVERE: Communication failure while joining agent platform: No ICP active
  jade.core.IMTPException: No ICP active
  </code></pre>
  
  <p>I want to run it multiple times without manually re-starting. Here is my JADE code (took help from <a href="https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html" rel="nofollow noreferrer">https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html</a>):</p>
  
  <pre><code>public class MatlabComAgent extends Agent
  {
  ServerSocket srvr = null;
      Socket skt = null;
      BufferedReader in;
      PrintWriter out;
      String ip = "localhost";
      String filePath;
      int port = 1234;    
  
  protected void setup() 
      {
          // Get arguments
          Object[] args = getArguments();
          filePath = (String) args[0];
  
          // Create the TCP connection
          try 
          {
              // Create server and socket
              srvr = new ServerSocket(port);
              skt = srvr.accept();
  
              // Create writer and reader to send and receive data
              out = new PrintWriter(skt.getOutputStream(), true);
              in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
          } 
          catch (IOException e) 
          {
              e.printStackTrace();
          }
  
          // Send a message to the tester to say its can start sending requests
          sendMessage("Tester","","start-now",ACLMessage.INFORM);
  
          // Run behavior
          CommWithMatlab commWithMatlab = new CommWithMatlab();
          addBehaviour(commWithMatlab);
  
      } // End setup
  </code></pre>
  
  <p>Code for Matlab connection:</p>
  
  <pre><code>% Create TCP/IP object 't'. Specify server machine and port number.
  % Open the connection with the server
  t = tcpip('localhost', 1234);
  set(t, 'InputBufferSize', 30000);
  set(t, 'OutputBufferSize', 30000);
  pause(0.1)
  fopen(t);
  disp('Connection with JADE established')
  </code></pre>
  
  <p>I found interesting notes on "socket server which allows multiple connections via threads and Java" <a href="https://stackoverflow.com/questions/5109654/creating-a-socket-server-which-allows-multiple-connections-via-threads-and-java">Creating a socket server which allows multiple connections via threads and Java</a> page, however, I am not able to do it completely what is said here. May be I am missing something here. <strong>(2)</strong> I am confused should I edit my Matlab code and/or JADE code for multi-threading.</p>
  
  <p>Here is my code that I tried:</p>
  
  <pre><code>protected void setup() 
      {
          // Get arguments
          Object[] args = getArguments();
          filePath = (String) args[0];
  
          // Create the TCP connection
          try 
          {
              srvr = new ServerSocket(port);              
              Runnable connectionHandler = new ConnectionHandler(skt);
              new Thread(connectionHandler).start();
          } 
          catch (IOException e) 
          {
              e.printStackTrace();
          }
  </code></pre>
  
  <p>Here is new ConnectionHandler class:</p>
  
  <pre><code>public class ConnectionHandler implements Runnable {
  private Socket sk=null; //initialize in const'r
     BufferedReader in;
     PrintWriter out;
  
     public ConnectionHandler(ServerSocket skt) throws IOException
     {
         sk = skt.accept();
         out = new PrintWriter(sk.getOutputStream(), true);
          in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
     }
  
     public void run() {
  
         try 
          {
  
              // Create writer and reader to send and receive data
              out = new PrintWriter(sk.getOutputStream(), true);
              in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
          } 
          catch (IOException e) 
          {
              e.printStackTrace();
          }
  
      }
  </code></pre>
  
  <p>}</p>
  
  <p>But I got some erorr "java.lang.NullPointerException". Can someone help me to properly code it, what I am missing. Also, <strong>(3)</strong> this run() in ConnectionHandler class will be invoked automatically? I was confused so I create writer and reader inside  Connectionhandler class and its run(). Can I simply make my MatlabComAgent class as multithread without adding any new class. I can make my class as </p>
  
  <pre><code>public class MatlabComAgent extends Agent implements Runnable
  {....
  ....
  }
  </code></pre>
  
  <p>Should I also put the following inside ConnectionHandler class?</p>
  
  <pre><code>// Send a message to the tester to say its can start sending requests
          sendMessage("Tester","","start-now",ACLMessage.INFORM);
  
      // Run behavior
      CommWithMatlab commWithMatlab = new CommWithMatlab();
      addBehaviour(commWithMatlab);
  </code></pre>
  
  <p>Here, CommWithMatlab class extends SimpleBehavior containg required actions that further passes commands from Matlab to PowerWorld (using another connection). One example is like:</p>
  
  <pre><code>class CommWithMatlab extends SimpleBehaviour
      {
  
          private static final long serialVersionUID = 8966535884137111965L;
          @Override
          public void action() 
          {   
  
              // Wait for a message from another agent requesting something
              ACLMessage msg = blockingReceive();
  
              // If this is to open a case
              if(msg.getConversationId().equals(OPEN_CASE))
              {
                  openCase(msg.getContent());
              }
  }
  </code></pre>
  
  <p>I can simple pass arguments to addagent() and can call runJade(). The following are my JADE run functions using agents: </p>
  
  <pre><code>//Runs JADE and starts the initial agents
  
      public static void runJade() throws ControllerException
      {
          // Launch JADE platform
          Runtime rt = Runtime.instance();
          Profile p;
          p = new ProfileImpl();
          cController = rt.createMainContainer(p);            
          rt.setCloseVM(true);
  
          // Launch Powerworld interface agent
          addAgent(PWRWORLD_NAME, PWRWORLD_CLASS, null);
          addAgent(PWRWORLD_TESTER_NAME, PWRWORLD_TESTER_CLASS, null);
          //addAgent(PWRWORLD_TESTER_NAME2, PWRWORLD_TESTER_CLASS2, null);
      }
  
      private static void addAgent(String name, String type, String arg) throws ControllerException 
      {       
          Object[] argsObj = {arg};
          AgentController ac = cController.createNewAgent(name, type, argsObj);
          ac.start();
      }
  </code></pre>
  
  <p><strong>(4)</strong> I have a different program that also creates the same connection. When I try to run one program when other is running, it again throws binding error. However, these programs are completely separate. One program uses port 1234 and other 1239. However, system always assign local port to 1099 to both programs, hence throw binding error in this case.
  Any help is appreciable!</p>