Hello Members,

The following Client/Server does a simple chat where I am able to send and receive one line at a time. How should I proceed if I were to send at aleast 4-5 lines at a time.
Any help (with some sample pseudocode) would be of immense help.

Thank you!

SERVER:

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

public class ChatServer
{  private Socket          socket   = null;
   private ServerSocket    server   = null;
   private DataInputStream streamIn =  null;
   private DataOutputStream streamOut = null;
    private DataInputStream  console   = null;
    
   public ChatServer(int port)
   {  try
      {  System.out.println("Binding to port " + port + ", please wait  ...");
         server = new ServerSocket(port);  
         System.out.println("Server started: " + server);
         System.out.println("Waiting for a client ..."); 
         socket = server.accept();
         System.out.println("Client accepted: " + socket);
         open();
         boolean done = false;
         while (!done)
         {  try
            {  String line = streamIn.readUTF();
               System.out.println("Client says  : " + line);
               String line_1 = console.readLine();
               System.out.println("Server says  : " + line_1);
               streamOut.writeUTF(line_1);
               streamOut.flush();
               done = line.equals("bye") || line_1.equals("bye");
            }
            catch(IOException ioe)
           {
             done = true;
            }
         }
         close();
      }
      catch(IOException ioe)
      {  System.out.println(ioe); 
          
      }
   }
   public void open() throws IOException
   {  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
      console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void close() throws IOException
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
      if (console   != null)  console.close();
      if (streamOut != null)  streamOut.close();
   }
   public static void main(String args[])
   {  ChatServer server = new ChatServer(2000);
   }
}

CLIENT:

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

public class ChatServer
{  private Socket          socket   = null;
   private ServerSocket    server   = null;
   private DataInputStream streamIn =  null;
   private DataOutputStream streamOut = null;
    private DataInputStream  console   = null;
    
   public ChatServer(int port)
   {  try
      {  System.out.println("Binding to port " + port + ", please wait  ...");
         server = new ServerSocket(port);  
         System.out.println("Server started: " + server);
         System.out.println("Waiting for a client ..."); 
         socket = server.accept();
         System.out.println("Client accepted: " + socket);
         open();
         boolean done = false;
         while (!done)
         {  try
            {  String line = streamIn.readUTF();
               System.out.println("Client says  : " + line);
               String line_1 = console.readLine();
               System.out.println("Server says  : " + line_1);
               streamOut.writeUTF(line_1);
               streamOut.flush();
               done = line.equals("bye") || line_1.equals("bye");
            }
            catch(IOException ioe)
           {
             done = true;
            }
         }
         close();
      }
      catch(IOException ioe)
      {  System.out.println(ioe); 
          
      }
   }
   public void open() throws IOException
   {  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
      console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void close() throws IOException
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
      if (console   != null)  console.close();
      if (streamOut != null)  streamOut.close();
   }
   public static void main(String args[])
   {  ChatServer server = new ChatServer(2000);
   }
}

Recommended Answers

All 9 Replies

You posted your server code twice, and didn't post your client code. Please fix.

Hello Kramerd,

Sorry about that! Following is my Client code:

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

public class ChatClient
{  private Socket socket              = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;
   private DataInputStream streamIn =  null;
   
   public ChatClient(String serverName, int serverPort)
   {  System.out.println("Establishing connection. Please wait ...");
      try
      {  socket = new Socket(serverName, serverPort);
         System.out.println("Connected: " + socket);
         start();
      }
      catch(UnknownHostException uhe)
      {  System.out.println("Host unknown: " + uhe.getMessage());
      }
      catch(IOException ioe)
      {  System.out.println("Unexpected exception: " + ioe.getMessage());
      }
      boolean done = false;
      while (!done)
      {  try
         { 
            String line = console.readLine();
            System.out.println("Client says  : " + line);
            streamOut.writeUTF(line);
            streamOut.flush();
            String line_1 = streamIn.readUTF();
            System.out.println("Server says  : " + line_1);
            done = line.equals("bye") || line_1.equals("bye");
                
         }
         catch(IOException ioe)
         { 
             done = true;
             System.out.println("Sending error: " + ioe.getMessage());
         }
      }
      stop();
   }
   public void start() throws IOException
   {  console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
      streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
   }
   public void stop()
   {  try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (socket    != null)  socket.close();
         if (streamIn != null)  streamIn.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ...");
      }
   }
   public static void main(String args[])
   {  ChatClient client = null;
      client = new ChatClient("localhost", 2000);
   }
}

First, DataInputStream's readLine method has been deprecated, so you should read the documentation on how to fix that. But that being said, you could replace the line

String line = console.readLine();

with a loop that reads lines until EOF (readLine will return null at EOF), and store the lines in a buffer. Then send the whole buffer to the server instead of just the one line. Your buffer can also be a String and you can just append each line on to the last.

I could be wrong, but I believe when you're typing at the console in the client window, you can type either CTRL-d or CTRL-z depending on your OS to signal EOF. So you would type as many lines as you like and then type one of the EOF signals, and then the client program will bundle up your message and send it to the server.

Please write back to say whether this worked or not.

Hello kramerd,

Thanks a lot for the help!! I will surely get back to you.

Regards

Hello Kramerd,

Is this the correct syntax for what you suggested? I am posting just the while loop code fragment:

while (!done)
         {  try
            {  String line = streamIn.readUTF();
               System.out.println("Client says  : " + line);
               String line_1 = "";
              
               while (console.readLine()!= "" )
               {
               line_1 += console.readLine();
               }
               System.out.println("Server says  : " + line_1);
               streamOut.writeUTF(line_1);
               streamOut.flush();
               done = line.equals("bye") || line_1.equals("bye");
            }
            catch(IOException ioe)
           {
             done = true;
            }
         }

Kindly let me know.

Thank you!!

Not quite right. The readLine call on line 7 will throw away every odd line (lines 1, 3, 5, ... etc.) from the input. I don't think you want to lose those lines. Also, "" is called the empty string, and is not the same as null. Try something like this:

String buffer = "", line;
while ((line = console.readLine()) != null) {
   buffer += line;
}

Hello Kramerd,

Thank you for the reply! Sorry to bother you again. I tried as you suggested and I am unable to send/receive any messages. Following is the code fragment of my Client and Server:

CLIENT:

boolean done = false;
      while (!done)
      {  try
         { 
            String buffer = "", line1;
               while ((line1 = console.readLine()) != null) {
                   buffer += line1;
                }
            System.out.println("Client says  : " +  buffer);
            streamOut.writeUTF( buffer);
            streamOut.flush();
            String line_1 = streamIn.readUTF();
            System.out.println("Server says  : " + line_1);
            done = line_1.equals("bye") || buffer.equals("bye");
                
         }
         catch(IOException ioe)
         { 
             done = true;
             System.out.println("Sending error: " + ioe.getMessage());
         }
      }

SERVER:

boolean done = false;
         while (!done)
         {  try
            {  String line = streamIn.readUTF();
               System.out.println("Client says  : " + line);
               String buffer = "", line1;
               while ((line1 = console.readLine()) != null) {
                   buffer += line1;
                }
               System.out.println("Server says  : " + buffer);
               streamOut.writeUTF(buffer);
               streamOut.flush();
               done = line.equals("bye") || buffer.equals("bye");
            }
            catch(IOException ioe)
           {
             done = true;
            }
         }

Any help is greatly appreciated!!

Thank you!

Sorry, I had copied the wrong code. I think what you have is working fine. Just remember you have to type CTRL-z to signal EOF after your input.

For example, starting in the client console, you could type something like this:

Hello from the client
This is line two
Some other text
^z

Then in the server console, do the same:

Received message from client
This is the server's 2nd line
^z

To make those ^z marks, hold down the control key and then press z. Then you need to hit enter the last time and the message should go through.

Hello Kramer,

It works perfectly now!!

Thank you for your patience and advise!!

Regards,
sciprog1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.