Solved

Getting two different classes/programs interacting

Posted on 2006-11-09
4
180 Views
Last Modified: 2010-03-31
For an AI program I am making I need to get two programs interacting - I am doing this by using sockets and a threads.

This program is a smaller version of th AI program. There are two of these programs - opposites i.e. where one says female the other says male and so on.

Ok this is what should happen:

-Program starts and background threads starts with it (always reading input).

-Command is issued by the other program ("mate").

-This triggers the connect() method which sends a command to the other program (action triggered) therefore they have interacted.

Please give me any hints as to why this does not work.

Thanks
John

import java.util.Scanner;
import java.util.Vector;
import java.util.Random;
import java.io.*;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
 
//set path="C:\Program Files\Java\jdk1.5.0_08\bin"
 
public class AIPetTest
{
      public Socket socket = null;
      public String command = "";
      public static Vector<String> commands = null;
      public String line = null;
 
      public String start()
      {
            backgroundThread.start();
 
            Scanner command = new Scanner(System.in);
            String commandIssued = command.nextLine();
 
            if(commandIssued.equals("mate"))
            {
                  try
                  {
                        connect("mate");
                  }
                  catch(Exception e)
                  {
                        System.err.println("Caught Exception: " + e.getMessage());
                  }
            }
            return null;
      }
 
      public void connect(String update) throws Exception
      {
            System.out.println(update);
 
          try
          {
                  System.out.println("Connection made");
                socket = new Socket("localhost", 1977); // throws Exception below, if no connection is possible
 
          }
          catch(ConnectException ce)
          {
                System.out.println("Connection lost");
                socket = new ServerSocket(1977).accept();
                // no connection was possible, so make app server
                //socket = new ServerSocket(1977).accept();
                // be aware that accept is blocking!
            }
 
            command = commands.remove(0);  // Take the 1st object out
 
            System.out.println("Command: " + command);
 
            if(command.equals("updateMale")) // incoming
            {
                  System.out.println("Mating");
            }
 
 
            socket.getOutputStream().write(("updateFemale").getBytes());
 
            //socket.close();
    }
 
    Thread backgroundThread = new Thread(new Runnable() // reads all incoming messages and stores them in a vector
    {
          public void run()
          {
                  System.out.println("Thread running");
 
                  commands = new Vector<String>();
                  try
                  {
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 
                        while(true)
                        {
                               line = in.readLine();
 
                               if(line == null)
                               {
                                     break; // out of the while
                               }
 
                               commands.add(new String(line + '\n'));
                        }
                        in.close();
                  }
                  catch(IOException ioe)
                  {
                        System.err.println("Caught Exception: " + ioe.getMessage());
                  }
          }
    });
 
      public static void main(String[] args)
      {
            AIPetTest pet = new AIPetTest();
            pet.start();
      }
}
0
Comment
Question by:john8932
  • 2
  • 2
4 Comments
 
LVL 13

Expert Comment

by:marchent
ID: 17905970
>>socket.getOutputStream().write(("updateFemale").getBytes());

OutputStream os = sock.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
pw.println("...");

the true inside the PrintWriter constructor will autoflush the output.

~marchent~
0
 

Author Comment

by:john8932
ID: 17906030
What does the autoflush do?

Do you suggest I replace the code you mentioned?

I forgot to say that when I run this I always get this exception although the  program carries on and allows me to enter the mate command which then gives another exception:

Thread running
Exception in thread "Thread-0" java.lang.NullPointerException
        at AIPetTest2$1.run(AIPetTest2.java:84)
        at java.lang.Thread.run(Thread.java:595)

mate
mate
Connection made
Caught Exception: Array index out of range: 0

Cheers
0
 
LVL 13

Accepted Solution

by:
marchent earned 250 total points
ID: 17906228
i think this is a client side program, did u implemented a serverside program for this code? otherwise u have to implement the serverside code.

>>BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
socket.getInputStream() returns null, so null pointer exception.
0
 

Author Comment

by:john8932
ID: 17906270
I think I will simplify this so that one program is the server - always listening for a command, and one is the client. It runs second. It connects then it sends a command.

If you can get the other way working i.e. connect both ways alternatively then please do as this would be better.

This is a client side program.

Thanks
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now