Link to home
Start Free TrialLog in
Avatar of Idarhillgaar
IdarhillgaarFlag for Ireland

asked on

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


ASKER CERTIFIED SOLUTION
Avatar of bhaskar20001
bhaskar20001
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.

Avatar of CEHJ
You need to maintain a List of clients and then iterate it, sending to each
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> 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.
Avatar of aozarov
aozarov

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.
The difference is trivial :) And makes no difference.

A better solution would really be to move the server thread into a seperate class anyway.
>>  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
...
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
   -- 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 :)
Problem 1 will be resolved once he will apply bhaskar20001 advice.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Idarhillgaar

ASKER

Very good answers from all - will implement many of these solutions.

Thanks all

--
Idar