Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: CCN(Computer Communication and Network Systems)

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default CCN(Computer Communication and Network Systems)

    Hi I have some knowledge about programming in general. However, it's my first time in programming in trying to communicate from one machine to another and I find it rather exiting. I have managed to communicate using a "Server.java" and "Client.java" class successfully by transmitting messages to a single server. My next task would be to create a buffer (string array) on server side and the next part is important "after sending 10 messages from "Client", "Server" should print a message "BUFFER FULL"." following are my two similar classes, and cannot wait to see this working, can somebody please help me? :-):

    import java.io.*; 
    import java.net.*; 
     
    public class TCPMultiThreadServer { 
     
     
    private static ServerSocket welcomeSocket;
     
    private static final int PORT = 1234;
    private static int clientNo =1;
      public static void main(String argv[]) throws Exception 
        { 
     
     
         System.out.println("Opening port...\n");
     
         try
    		{
               welcomeSocket = new ServerSocket(PORT); 
     
     
    }
    		catch (IOException e)
    		{}
     
     
     
         do { 
     
                Socket client = welcomeSocket.accept();
                System.out.println("\nNew client accepted.\n");
     
                //Create a thread to handle communication with
    	    //this client and pass the constructor for this
    	    //thread a reference to the relevant socket...
     
                TCPMultiThreadServer.ClientHandler handler = 
                    new TCPMultiThreadServer().new ClientHandler(client,clientNo);
     
                handler.start(); //this method calls run.
     
     
    		clientNo++; 
     
    	 }while (true);
        }
     
     
     
    class ClientHandler extends Thread
    {
    	private Socket client;
    	private BufferedReader inFromClient;
            private BufferedReader text_to_Client;
     
    	private DataOutputStream outToClient;
    	public int clientNo;
     
           public boolean stopping; 
    	public ClientHandler(Socket socket, int clientNos)
    	{
    		//Set up reference to associated socket...
    		client = socket;
    		clientNo= clientNos;
     
    		try
    		{
    			inFromClient = 
                  new BufferedReader(new
                      InputStreamReader(client.getInputStream()));
                  text_to_Client =
                  new BufferedReader(new InputStreamReader(System.in));
     
     
                outToClient = 
                  new DataOutputStream(client.getOutputStream()); 
    		}
    		catch(IOException e)
    		{}
    	}
     
    	public void run()
    	{
     
    		try
    		{
     
        stopping = false;
    		     String clientSentence; 
                         String capitalizedSentence;
                         Thread mythread = Thread.currentThread(); 
     
     
     do
     {
     
           //Accept message from client on
    	   //the socket's input stream...
     
            OutputStream sout = client.getOutputStream();
     		// Just converting them to different streams, so that string handling becomes easier.
     
     
        	DataOutputStream text_to_send = new DataOutputStream(sout);
     
                   clientSentence = inFromClient.readLine();
                   System.out.println("Message received from client number " + clientNo + ": "+ clientSentence);
                   System.out.println("Enter Message: ");
                   clientSentence = text_to_Client.readLine();
                   //capitalizedSentence = clientSentence.toUpperCase() + '\n';
                   //int charCount = clientSentence.length();
                   text_to_send.writeUTF(clientSentence);
                   System.out.println("Your message: " + clientSentence);
                   //outToClient.write(charCount);
     
             // System.out.println("\nlength: " + charCount);
     
              if (mythread.activeCount() == 2 && (clientNo ==0 || clientNo >0)  && clientSentence.equals("E"))
                     System.exit(0);
     
           } while(!clientSentence.equals("E"));
     
     
            client.close();
             } catch(IOException e)
      {} 
     
        } 
    } 
    }
     
     
    import java.io.*; 
    import java.net.*; 
    class TCPClient1 { 
     
        public static void main(String argv[]) throws Exception 
        { 
            String sentence; 
            String modifiedSentence; 
     
            BufferedReader inFromUser = 
              new BufferedReader(new InputStreamReader(System.in)); 
     
            Socket clientSocket = new Socket("localhost",1234);
     
            DataOutputStream outToServer = 
              new DataOutputStream(clientSocket.getOutputStream()); 
     
           InputStream sin = clientSocket.getInputStream();
     
     
     			// Just converting them to different streams, so that string handling becomes easier.
    			DataInputStream inFromServer = new DataInputStream(sin);
     
    try{
     
      do  {
     
           System.out.print("Enter message: ");
            sentence = inFromUser.readLine(); 
     
            outToServer.writeBytes(sentence + '\n'); 
            System.out.print("Message sent! please wait for server message");
            modifiedSentence = inFromServer.readUTF();
     
            System.out.println("FROM SERVER: " + modifiedSentence); 
     
            } while(!sentence.equals("CLOSE"));      
      } catch(IOException e)
      {} 
            clientSocket.close();    
        } 
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,320
    Thanks
    56
    Thanked 2,374 Times in 2,345 Posts

    Default Re: CCN(Computer Communication and Network Systems)

    What does the code do now when it is executed? Please copy the full contents of the consoles and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: CCN(Computer Communication and Network Systems)

    Hi there, when the first class "TCPMultiThreadServer" is ran, it prints:

    TCPMultiThreadServer:
    "run:
    Opening port..."

    I am then expected to run "TCPClient1" and that prints:

    TCPClient1
    run:
    Enter message: hi
    Message sent! please wait for server message "(I hit enter)

    the messages are exchanged between the two classes:

    TCPMultiThreadServer:
    "
    run:
    Opening port...


    New client accepted.

    Message received from client number 1: hi
    Enter Message:
    "

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,320
    Thanks
    56
    Thanked 2,374 Times in 2,345 Posts

    Default Re: CCN(Computer Communication and Network Systems)

    Here are some tools and ideas I use for debugging client-server code. Execute client and server in one JVM by putting this main() in a testing class and executing it:
     
      public static void main(final String[] args) {
          Thread t1 = new Thread(new Runnable() {
             public void run() {
                try{TCPMultiThreadServer.main(args);}catch(Exception x){x.printStackTrace();}
             }
          });
          t1.start();
     
          try{Thread.sleep(100);}catch(Exception x){}
     
          Thread t2 = new Thread(new Runnable() {
             public void run() {
                try{TCPClient1.main(args);}catch(Exception x){x.printStackTrace();}
             }
          });
          t2.start();
     
     
          // wait and exit
          try{Thread.sleep(5000);}catch(Exception x){}
          System.out.println("Exiting main");
          System.exit(0);
     
       }  //  end main()>>>>>>>>>>>>>>>>>>>>>>>>>>
    Change the source of input for the program by replacing System.in with a StringReader:
                  //  All input to come from String in StringReader
                  StringReader sr = new StringReader("msg1 and text\n2\n3\n4\n5\n6\n7\n8\n9\nE\n1\n2\n3\n");
                  text_to_Client =
                      new BufferedReader(sr); //new InputStreamReader(System.in));
    I get this on the console when I execute:
    Running: java -client -cp . TCPMultiThreadServerTest

    Opening port...


    New client accepted.

    Enter message: Message sent! please wait for server messageMessage received from client number 1: hi there
    Enter Message:
    FROM SERVER: msg1 and text
    Enter message: Message sent! please wait for server messageYour message: msg1 and text
    Message received from client number 1: 2
    Enter Message:
    FROM SERVER: 2
    Enter message: Message sent! please wait for server messageYour message: 2
    Message received from client number 1: 3
    Enter Message:
    FROM SERVER: 3
    Enter message: Message sent! please wait for server messageYour message: 3
    Message received from client number 1: 4
    Enter Message:
    FROM SERVER: 4
    Enter message: Message sent! please wait for server messageYour message: 4
    Message received from client number 1: 5
    Enter Message:
    FROM SERVER: 5
    Enter message: Message sent! please wait for server messageYour message: 5
    Message received from client number 1: 6
    Enter Message:
    FROM SERVER: 6
    Enter message: Message sent! please wait for server messageYour message: 6
    Message received from client number 1: 7
    Enter Message:
    FROM SERVER: 7
    Enter message: Message sent! please wait for server messageYour message: 7
    Message received from client number 1: E
    Enter Message:
    FROM SERVER: 8
    Enter message: Message sent! please wait for server messageYour message: 8
    Message received from client number 1: 2
    Enter Message:
    FROM SERVER: 9
    Enter message: Message sent! please wait for server messageYour message: 9
    Message received from client number 1: 3
    Enter Message:
    FROM SERVER: E
    Enter message: Message sent! please wait for server messageYour message: E
    java.io.EOFException
    at java.io.DataInputStream.readUnsignedShort(Unknown Source)
    at java.io.DataInputStream.readUTF(Unknown Source)
    at java.io.DataInputStream.readUTF(Unknown Source)
    at TCPMultiThreadServerTest$TCPClient1.main(TCPMultiT hreadServerTest.java:197)
    at TCPMultiThreadServerTest$2.run(TCPMultiThreadServe rTest.java:22)
    at java.lang.Thread.run(Unknown Source)
    Exiting main

    0 error(s)
    BTW ALL catch blocks should have calls to the printStackTrace() method
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: CCN(Computer Communication and Network Systems)

    How would you call back to the printStackTrace(), sorry I understand what you mean but can't seem to do it. Can I see the syntax if possible? It's just that mines still on infinite no of messages lol :-) Thanks.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,320
    Thanks
    56
    Thanked 2,374 Times in 2,345 Posts

    Default Re: CCN(Computer Communication and Network Systems)

    It goes in the catch block:
    		catch (IOException e)
    		{e.printStackTrace();}

    infinite no of messages
    Add a counter and send the buffer full when the counter reaches the amount.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 6
    Last Post: July 25th, 2014, 06:55 AM
  2. Body Systems Class
    By lah2015 in forum Object Oriented Programming
    Replies: 2
    Last Post: September 17th, 2013, 12:44 AM
  3. Network communication hangs
    By droyhull in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 8th, 2011, 11:55 AM
  4. Code wise working of Computer Algebra Systems
    By helloworld922 in forum Java Theory & Questions
    Replies: 1
    Last Post: July 7th, 2009, 08:45 AM