Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Need help with streams, reader writer

streamwriter stream

  • Please log in to reply
4 replies to this topic

#1 the_flirt

the_flirt

    CC Lurker

  • Just Joined
  • Pip
  • 9 posts

Posted 14 April 2010 - 07:04 AM

I came up with the following code for sending a simple message from a server to a client and getting a reply back.

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

class ServerTest
{
    public static void main(String args[]) throws IOException
    {
        String ostr = "Hi this is the server!";
        String istr;
        BufferedReader br;
        BufferedWriter bw;
        ServerSocket ss = new ServerSocket(9999);
        System.out.println("Waiting for connection...");
        Socket s = ss.accept();
        System.out.println("Connection accepted!");
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bw.write(ostr);
        while((istr = br.readLine())!= null)
        {
            System.out.println(istr);
        }
        br.close();
        bw.close();
        s.close();
    }
}

//CLIENT
import java.io.*;
import java.net.*;

class ClientTest
{
    public static void main(String args[]) throws IOException
    {
        String ostr = "Hi this is the client!";
        String istr;
        BufferedReader br;
        BufferedWriter bw;
        Socket s = new Socket("127.0.0.1", 9999);
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        while((istr = br.readLine())!= null)
        {
            System.out.println(istr);
        }
        bw.write(ostr);
        br.close();
        bw.close();
        s.close();
    }
}
The connection is working. I get the connection accepted message. But the messages are not being displayed.
What am I doing wrong? Either there is a problem with sending and receiving. Or with displaying the received text.
Please help...
  • 0

#2 the_flirt

the_flirt

    CC Lurker

  • Just Joined
  • Pip
  • 9 posts

Posted 15 April 2010 - 04:29 AM

Is anyone even active on this forum?? :@
  • 0

#3 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 15 April 2010 - 07:59 PM

First... remember that you are using a BufferedWriter object, which maintains an internal buffer for which you need to use it's flush() method to send anything to the other side. Essentially, the BufferedWriter allows you to construct a significant message, with many lines that may be constructed in all sorts of fantastic programmatical ways, it literally could be data for anything, so the control is mostly given to the coder rather than the library. As such, you need to actually tell it to send it, not just expect to do so whenever it chooses. What you're getting trapped on is the readLine() method of a BufferedReader, which is having the client waiting for some kind of response from the server, and the server isn't furnishing one. These are the changes I made:
//SERVER
import java.io.*;
import java.net.*;

class ServerTest
{
    public static void main(String args[]) throws IOException
    {
        String ostr = "Hi this is the server!";
        String istr;
        BufferedReader br;
        BufferedWriter bw;
        ServerSocket ss = new ServerSocket(9999);
        System.out.println("Waiting for connection...");
        Socket s = ss.accept();
        System.out.println("Connection accepted!");
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bw.write(ostr);
        bw.newLine();
        bw.flush();
        System.out.println(br.readLine());
        br.close();
        bw.close();
        s.close();
    }
}
//CLIENT
import java.io.*;
import java.net.*;

class ClientTest
{
    public static void main(String args[]) throws IOException
    {
        String ostr = "Hi this is the client!";
        String istr;
        BufferedReader br;
        BufferedWriter bw;
        Socket s = new Socket("127.0.0.1", 9999);
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        System.out.println(br.readLine());
        bw.write(ostr);
        bw.newLine();
        bw.flush();
        br.close();
        bw.close();
        s.close();
    }
}
I eliminated the loop on both of them (it wasn't necessary for the demonstration, but don't do it in a real program, networking can be concurrency **), and for both of them I added the snippet
bw.newLine();
bw.flush();
The newLine is because of the readLine() method, which requires that a line end with either \n or \r, so a newLine character is necessary in the writing stream, and the newLine method happens to choose the appropriate one for the platform. The bw.flush() method is used to send the data to the other side of the connection, which is then read by readLine and interpreted properly. If you want to maintain a loop in the client that detects if br.readLine() is null, you'll have to close the connection manually from one of the sides within the loop.


The second thing, yes, people are active on this forum. It happens to be, however, that Java isn't a terribly popular language here. There are some people who use it, and a couple who are actually pretty good at it, but you'll find a lot more people here use C or C++. The Java forums may take you several days to get a desirable answer, IE one that actually helps you solve your problem, but people who know how to use Java will eventually show up and give you a hand. I know it can be difficult to be patient, especially if it's an assignment for school, but most people have jobs, family, friends, and otherwise are tangled up in their own lives. Answering questions on here is something we do after other stuff. :)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#4 the_flirt

the_flirt

    CC Lurker

  • Just Joined
  • Pip
  • 9 posts

Posted 17 April 2010 - 12:23 PM

Hi,
First of all, just so you know that I'm not one of those ungrateful people, I want to thank you. I really appreciate you taking your time out and writing such a descriptive reply. :)
I had created another thread where no one replied, so I just thought this forum might be dead. I apologize.

You told me that you had eliminated the loop, but that I shouldn't do that in the main program. But the program didn't work with the loop. It worked without the loop (like you demonstrated); The following code worked:
//SERVER
import java.io.*;
import java.net.*;

class ServerTest
{
    public static void main(String args[]) throws IOException
    {
        String ostr = "Hi this is the server!";
        String istr;
        BufferedReader br;
        BufferedWriter bw;
        ServerSocket ss = new ServerSocket(9999);
        System.out.println("Waiting for connection...");
        Socket s = ss.accept();
        System.out.println("Connection accepted!");
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bw.write(ostr);
        bw.newLine();
        bw.flush();
        istr = br.readLine();
        System.out.println(istr);
        br.close();
        bw.close();
        s.close();
    }
}

//CLIENT
import java.io.*;
import java.net.*;

class ClientTest
{
    public static void main(String args[]) throws IOException
    {
        String ostr = "Hi this is the client!";
        String istr;
        BufferedReader br;
        BufferedWriter bw;
        Socket s = new Socket("127.0.0.1", 9999);
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        istr = br.readLine();
        System.out.println(istr);
        bw.write(ostr);
        bw.newLine();
        bw.flush();
        br.close();
        bw.close();
        s.close();
    }
}
So what do I do?


Apart from that, you actually cleared one of my doubts; I never really understood when the message was actually being sent. Now I realize that without flush(); it never was being sent.
But this solution created another doubt: Without flush();, how did this following code work? It works perfectly... :crying: (and it also has the loop, where as the first 2 programs worked only without the loop...)
//SERVER
import java.net.*;
import java.io.*;

public class KServer
{
    public static void main(String[] args) throws IOException
    {
        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(4444);
        }
        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }
        Socket clientSocket = null;
        try
        {
            clientSocket = serverSocket.accept();
        }
        catch (IOException e)
        {
            System.err.println("Accept failed.");
            System.exit(1);
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        String inputLine = in.readLine();
        System.out.println("Client to Server "+inputLine);
        out.println("Hi CLIENT THIS IS THE SERVER!");
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}

//CLIENT
import java.io.*;
import java.net.*;

public class KClient
{
    public static void main(String[] args) throws IOException
    {
        Socket kkSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try
        {
            kkSocket = new Socket("127.0.0.1", 4444);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        }    
        catch (UnknownHostException e)
        {
            System.err.println("Error");
            System.exit(1);
        }    
        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;
        out.println("HI! THIS IS A CLIENT!");
        fromServer=in.readLine();
        System.out.println("Server to client: "+fromServer);
        out.close();
        in.close();
        stdIn.close();
        kkSocket.close();
    }
}
This is confusing. :crying:
  • 0

#5 the_flirt

the_flirt

    CC Lurker

  • Just Joined
  • Pip
  • 9 posts

Posted 23 April 2010 - 06:17 AM

Any answers?
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download