Results 1 to 13 of 13
  1. #1
    frederic202 is offline Member
    Join Date
    Mar 2010
    Posts
    7
    Rep Power
    0

    Default readLine() doesn't work

    Hi,
    Im kind of new at networkprogramming. Im making an easy chat program.
    I use a serverclass, a serverThread class and a simple client.
    I think the problem is in the serverThread class:
    Java Code:
    package domein;
    
    import java.io.*;
    import java.net.*;
    
    public class ServerThread extends Thread
    {
    	private ChatServer server;   // The Server that spawned us
    	private Socket socket;     // The Socket connected to our client
    	
    
    	public ServerThread( ChatServer server, Socket socket )
    	{
    		this.server = server;
    		this.socket = socket;
    		start();     // Start up the thread
    	}
    
    	public void run() // This runs in a separate thread when start() is called in the constructor.
    	{
    		try 
    		{
    			BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) );   // Create a bufferedreader for communication. the client is using a bufferedwriter to write to us
    			System.out.println( "thread is running: "+socket ); 
    			while (true)
    			{
    				String message = br.readLine() ;   // read the next message
    				System.out.println( "Sending "+message );
    				server.sendToAll( message );     // and have the server send it to all clients
    				//String nickname= br.readLine();
    				//server.sendTo(nickname, message);
    			}
    		} 
    		catch( EOFException ie ) 
    		{
    			// This doesn't need an error message
    		}
    		catch( IOException ie ) 
    		{
    			// This does; tell the world!
    			ie.printStackTrace();
    		} 
    		finally 
    		{
    			server.removeConnection( socket );     // The connection is closed for one reason or another, so have the server dealing with it
    		}
    	}
    }
    When i run the server and a client class, they will have a connection. But the last thing that will appear is "thread is running +socket info".
    So basically the String message = br.readLine() statement doesnt do anything. The client class is very basic at this time:
    Java Code:
    package domein;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    
    
    public class ClientTest {
    
    	    public static void main(String[] args) {
    	        try {
    	            InetAddress host = InetAddress.getLocalHost();
    	            int port = 6667;
    	            Socket socket = new Socket(host, port); // aanmaken clientsocket
    
    	            // ophalen input- en outputstream van de socket
    	            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // true: automatische flush na elke print
    	            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    	            
    	            String message= "test"; 
    	            out.write(message);
    	          
    	            
    	            System.out.println("Antwoord van de server: " + in.readLine()); // antwoord ophalen via inputstream socket
    
    	            socket.close(); // socket afsluiten (input- en outputstream worden automatisch afgesloten)
    	        }
    	        catch (IOException ex) {
    	            ex.printStackTrace();
    	        }
    	    }
    	}
    So normally "test" should have been written in my console screen. But it doesnt.
    Does anyone now an answer to my problem?

    Thanx,
    grtz frederic
    Last edited by Norm; 11-08-2011 at 01:04 PM. Reason: added code tags

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: readLine() doesn't work

    For future reference, wrap you code in the code tags.

    Be sure sure to flush your output streams when writing to them is complete (and you wish the client to read the information).

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    Also readLine() wants a new line character before it will return a line. It will wait until it gets one.

  4. #4
    frederic202 is offline Member
    Join Date
    Mar 2010
    Posts
    7
    Rep Power
    0

    Default Re: readLine() doesn't work

    ok I put a out.flush() after the out.write().
    And how do i add a new line char in
    Java Code:
    String message= "test";
    out.write(message);
    It looks really easy but it wont work with \n

    thnx

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    it wont work with \n
    What happened when you added the \n?

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    The ChatServer code is missing if anyone wants to test this code.

  7. #7
    frederic202 is offline Member
    Join Date
    Mar 2010
    Posts
    7
    Rep Power
    0

    Default Re: readLine() doesn't work

    Here is the ChatServer code:

    Java Code:
    package domein;
    
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class ChatServer
    {
    	private ServerSocket ss;    // The ServerSocket we'll use for accepting new connections
    								// A mapping from sockets to DataOutputStreams. This will
    								// help us avoid having to create a DataOutputStream each time
    								// we want to write to a stream.
    	private Hashtable outputStreams = new Hashtable();
    	
    	public ChatServer( int port ) throws IOException      // Constructor and while-accept loop all in one.
    	{
    		listen( port );   // All we have to do is listen
    	}
    	
    	private void listen( int port ) throws IOException
    	{
    		ss = new ServerSocket( port );    // Create the ServerSocket
    		System.out.println( "Listening on "+ss );
    		while (true)    // Keep accepting connections forever
    		{			
    			Socket s = ss.accept();    // Grab the next incoming connection
    			System.out.println( "Connection from "+s );
    			BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(s.getOutputStream()) );        // Create a bufferedwriter for writing data to the other side
    			outputStreams.put( s, bw );	 // Save this stream so we don't need to make it again
    
    			new ServerThread( this, s );	// Create a new thread for this connection, and then forget
    		}
    	}
    
    	public Enumeration getOutputStreams()		// Get an enumeration of all the OutputStreams, one for each client that is connected
    	{
    		return outputStreams.elements();
    	}
    
    	public void sendToAll( String message ) 	// Send a message to all clients 
    	{
    		synchronized( outputStreams ) // We synchronize on this because another thread might be calling removeConnection() and this would screw us up as we tried to walk through the list
    		{
    			for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) 
    			{
    				BufferedWriter bw = (BufferedWriter)e.nextElement();    // ... get the output stream ...
    				try    
    				{
    					bw.write( message );   // ... and send the message
    				} catch( IOException ie ) { System.out.println( ie ); }
    			}
    		}
    	}
    	
    	public void sendTo(String nickname, String message)
    	{
    		synchronized( outputStreams ) // We synchronize on this because another thread might be calling removeConnection() and this would screw us up as we tried to walk through the list
    		{
    			for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) 
    			{
    				Socket s = (Socket)e.nextElement();    // ... get the output stream ...
    				
    				try    
    				{
    					BufferedReader br = new BufferedReader( new InputStreamReader(s.getInputStream()) ); 
    					if(nickname== br.readLine())   //TODO moet aangepast worden, maar geen idee hoe nickname wordt ingelezen 
    						((DataOutputStream)s.getOutputStream()).writeUTF(message);
    				} catch( IOException ie ) { System.out.println( ie ); }
    			}
    		}
    	}
    
    	public void removeConnection( Socket s )   // Remove a socket, and it's corresponding output stream, from our list. This is usually called by a connection thread that has discovered that the connecting to the client is dead.
    	{
    		synchronized( outputStreams )   // Synchronize so we don't mess up sendToAll() while it walks down the list of all output streams
    		{
    			System.out.println( "Removing connection to "+s );
    			outputStreams.remove( s );	  // Remove it from our hashtable/list
    			try 
    			{
    				s.close();     // Make sure it's closed
    			} 
    			catch( IOException ie ) 
    			{
    				System.out.println( "Error closing "+s );
    				ie.printStackTrace();
    			}
    		}
    	}
    
    }

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    What does the debug println out put look like when you execute this code?

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    Have you tried what was recommended in post#2?

  10. #10
    frederic202 is offline Member
    Join Date
    Mar 2010
    Posts
    7
    Rep Power
    0

    Default Re: readLine() doesn't work

    Yes I added the flush, after the write() statement in the client :)

    When I run my server and my client, then this is my output:
    Java Code:
    Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=6667]
    Connection from Socket[addr=/172.18.22.189,port=1511,localport=6667]
    thread is running: Socket[addr=/172.18.22.189,port=1511,localport=6667]
    So basically it never reaches the System.out.println( "Sending "+message ) statement in the serverthread class

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    Sorry, I don't think you have tried the combinations that were suggested. I made those changes and get the following output:


    Running: F:\Java\jre6\bin\java.exe -classpath D:\JavaDevelopment;.;..\. -Xmx128M ClientServer5

    CT sending msg
    CT waiting for msg
    CS Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=6667]
    CS Connection from Socket[addr=/192.168.1.64,port=1139,localport=6667]
    ST thread is running: Socket[addr=/192.168.1.64,port=1139,localport=6667]
    ST Sending mag=test message from client
    sTA sending msg=test message from client
    CT Antwoord van de server: test message from client
    CT exiting
    sTA exiting
    Removing connection to Socket[addr=/192.168.1.64,port=1139,localport=6667]
    ST run exiting

  12. #12
    frederic202 is offline Member
    Join Date
    Mar 2010
    Posts
    7
    Rep Power
    0

    Default Re: readLine() doesn't work

    I just added a out.flush() after the out.write() in the clientTest klasse.
    What else did you add? Im sorry its the first time i do this :)

    grtz

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,411
    Rep Power
    25

    Default Re: readLine() doesn't work

    I said in post#3 and post#5 to use a \n
    Did you try that?

Similar Threads

  1. JFileChooser doesn't work as it should!
    By fioan89 in forum AWT / Swing
    Replies: 1
    Last Post: 09-13-2011, 02:06 PM
  2. Jar doesn't work
    By mad72584 in forum New To Java
    Replies: 35
    Last Post: 08-07-2011, 05:22 PM
  3. why this doesn't work?
    By hitesh_public in forum New To Java
    Replies: 5
    Last Post: 08-09-2010, 08:07 AM
  4. Why doesn't this work?
    By Corder10 in forum New To Java
    Replies: 1
    Last Post: 07-04-2009, 10:33 PM
  5. my loop doesn't work.. pls help???
    By ashton in forum New To Java
    Replies: 5
    Last Post: 01-16-2009, 08:24 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •