?
Solved

Problem receiving string to Client from threaded server.

Posted on 2005-04-02
16
Medium Priority
?
229 Views
Last Modified: 2010-03-31
I can read sentences from client on server, even multiple clients, but I cannot display all clients messages back to each client (Some kind of broadcast messages).

Problem 1: Cannot broadcast back all client messages to all clients - need example code
problem 2: How to initiate both client and server from the Test class - description of how I would proceed is sufficiesnt on problem 2

CLIENT:

String sentence;
String serverSentence;            
try
{      
      Socket s = new Socket("172.18.5.192", 4444);                                          
      BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));      
      DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());                        
      BufferedReader inFromServer = new BufferedReader (new InputStreamReader(s.getInputStream()));
      while(true) //Allows to write more than one message
      {
            sentence = inFromUser.readLine();  //Read sentences from user
            //serverSentence = inFromServer.readLine(); //reads data from server <------ This is the problem
            outToServer.writeBytes(sentence + '\n'); //Send the sentences to the Server
            if (sentence.equals("exit")) break; //Exit program when typing EXIT
                                .....etc

SERVER:
import java.io.*;
import java.net.*;

class TCPServer extends Thread //Where this is reffered to
{
      Socket s;      //Establish Socket
      String clientSentence; //Sentence from client
      String clientID; //added clientId to String      
      
      TCPServer ( Socket s ) //invoke thread to be socket s
        {
          this.s = s ;      //Inherit thread
          //start();  //started in public main instead
        }
        
  public void run () //Dedicated server funtionality for threads
  {
    try
    {
            BufferedReader inFromClient = new BufferedReader (new InputStreamReader(s.getInputStream()));  //Read Client String
            DataOutputStream outToClient = new DataOutputStream(s.getOutputStream());      //Send String to client temp
            clientID = (s.getInetAddress ().getHostName ()); //String is client ip address
            System.out.println (clientID + " Client Connected"); //Message when a client has connected to server.            
            
            //Loop so that client can send indefinetely strings
            while(true)
            {            
                  clientSentence = inFromClient.readLine(); //Read String from Client
                  if (clientSentence.equals("exit")) break; //Exits loop for the thread when client x 'exit'
                  System.out.println("In from :" + clientID + ": " +clientSentence); //Display client String on Server Side
                  outToClient.writeBytes(clientSentence);
          }
          System.out.println("Client: " + clientID + " Has disconnected from Server"); //Msg when client is lost
    }
      catch(SocketException se)
      {
          System.out.println("Socket Exception - Client "+ clientID +" disconnected"); //Error msg when a client disconnects
      }
      catch(IOException ioe)
      {
          System.out.println("IOExcep");
      }      
  }


TEST CLASS for SERVER:

import java.io.*;
import java.net.*;

class Test
{
 public static void main ( String args[] ) throws Exception
 {
    ServerSocket ss = new ServerSocket(4444);
      System.out.println ("Awaiting conections");

      
    while ( true )
    {
      Socket s = ss.accept();
      Thread t = new TCPServer(s);
      t.start();
    }
  }
}

--
Thanks for any help

Idar


0
Comment
Question by:Idarhillgaar
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
  • 2
  • +2
16 Comments
 
LVL 4

Accepted Solution

by:
bhaskar20001 earned 1400 total points
ID: 13689156
your client code should be..

while(true) //Allows to write more than one message
     {
          sentence = inFromUser.readLine();  //Read sentences from user
          outToServer.writeBytes(sentence + '\n'); //Send the sentences to the Server
          serverSentence = inFromServer.readLine(); //reads data from server
          if (sentence.equals("exit")) break; //Exit program when typing EXIT
0
 
LVL 4

Expert Comment

by:bhaskar20001
ID: 13689216
Because ,
 In your server code U r trying to read data from client first then only writing the same to client..
 So U have to write data first from ur client code on to server socket, then try read on server socket.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13689247
You need to maintain a List of clients and then iterate it, sending to each
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 
LVL 92

Expert Comment

by:objects
ID: 13689562
To start both client and server from your test class you would start two threads, one thread to run the server, and the other to run the client.
0
 
LVL 15

Assisted Solution

by:aozarov
aozarov earned 300 total points
ID: 13689569
bhaskar20001 have the right answer for you.
To more additions to improve your program.
1. This is minor but if you want to see the client 'exit' message the move  System.out.println("In from :"... before the if(...
2. More important, you should close the sockets (at least on the server side) to prevent resource leak. So repalce
 catch(IOException ioe)
     {
         System.out.println("IOExcep");
     }
with
 catch(IOException ioe)
     {
         System.out.println("IOExcep");
     }
finally
{
       try {s.close(); } catch (IOException ex) {/* normally you can ignore it*/}
}
0
 
LVL 15

Assisted Solution

by:aozarov
aozarov earned 300 total points
ID: 13689583
For running two of them together I think you can live with adding just one more thread:
in Test.main add before while (true)...:

something like:

new Thread("Client Thread")
{
public void run()
{
create client class and call its connect method
}
}.start();
0
 
LVL 92

Expert Comment

by:objects
ID: 13689590
> For running two of them together I think you can live with adding just one more thread:
> in Test.main add before while (true)...

Thats *two* threads.
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13689605
Right, but he does not need to *start* two of them. he can use
the main thread as he already did for the server side and just
start a new one for the client.
0
 
LVL 92

Expert Comment

by:objects
ID: 13689618
The difference is trivial :) And makes no difference.

A better solution would really be to move the server thread into a seperate class anyway.
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13689648
>>  The difference is trivial :) And makes no difference.
Right, but following its logic that was simpler thing to do .

>> A better solution would really be to move the server thread into a seperate class anyway.
Also right, but then there are many other things which would provide a better solution like:
    -- Use nio for better resource (ports, threads) scalebility
    -- Use thread pool to handle client requests instead of dispatching a new thread per client
...
0
 
LVL 92

Assisted Solution

by:objects
objects earned 300 total points
ID: 13689658
In fact you'll need a seperate class for the server thread anyway to implement problem 1.
The new class would include a thread to listen for server connections, and would manage all recieved connections.
So when a connection is recieved a new TCPServer is created and added to the list of connections.
You'dd also pass a reference to the server instance to the TCPServer constructor allowing it to access the list of connections.
And when a TCPServer classes the connection it would also need to notify the server so it could be removed from the list.
0
 
LVL 92

Expert Comment

by:objects
ID: 13689680
   -- Use nio for better resource (ports, threads) scalebility
    -- Use thread pool to handle client requests instead of dispatching a new thread per client

Bit beyond the scope of the question :)
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13689727
Problem 1 will be resolved once he will apply bhaskar20001 advice.
0
 
LVL 92

Assisted Solution

by:objects
objects earned 300 total points
ID: 13689868
Following article gives a simple example for handling broadcast

http://www.javaworld.com/javaworld/jw-01-1997/jw-01-chat_p.html
0
 

Author Comment

by:Idarhillgaar
ID: 13691231
Very good answers from all - will implement many of these solutions.

Thanks all

--
Idar
0
 
LVL 92

Expert Comment

by:objects
ID: 13693944
:)
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

743 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