Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 232
  • Last Modified:

Problem receiving string to Client from threaded server.

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
Idarhillgaar
Asked:
Idarhillgaar
  • 7
  • 5
  • 2
  • +2
5 Solutions
 
bhaskar20001Commented:
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
 
bhaskar20001Commented:
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
 
CEHJCommented:
You need to maintain a List of clients and then iterate it, sending to each
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
objectsCommented:
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
 
aozarovCommented:
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
 
aozarovCommented:
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
 
objectsCommented:
> 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
 
aozarovCommented:
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
 
objectsCommented:
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
 
aozarovCommented:
>>  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
 
objectsCommented:
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
 
objectsCommented:
   -- 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
 
aozarovCommented:
Problem 1 will be resolved once he will apply bhaskar20001 advice.
0
 
objectsCommented:
Following article gives a simple example for handling broadcast

http://www.javaworld.com/javaworld/jw-01-1997/jw-01-chat_p.html
0
 
IdarhillgaarAuthor Commented:
Very good answers from all - will implement many of these solutions.

Thanks all

--
Idar
0
 
objectsCommented:
:)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 7
  • 5
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now