Search code examples
javasocketsserversocketbufferedwriter

Simple client server program not working


Server program :

import java.io.*;
import java.net.*;
public class server
{
        public static void main(String args[])
        {
                try
                {
                ServerSocket ss=new ServerSocket(2000);
                Socket s=ss.accept();
                BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
                String str;
                while((str=br.readLine())!=null)
                {
                        System.out.println(str);
                }
                }
                catch(Exception e)
                {
                        System.out.println(e);
                }
        }
}

Client program :

import java.net.*;
import java.io.*;
public class client
{
        public static void main(String args[])
        {
                try
                {
                Socket s=new Socket("127.0.0.1",2000);
                String str;
                BufferedWriter br=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                br.write("\nHello World\n");
                }
                catch(Exception e)
                {
                        System.out.println(e);
                }
        }
}

The issues that I am facing are:

  1. No output.
  2. No Exception/Error is indicated.

Please explain me if am doing anything wrong. The problem might be the client has not written anything while the server is reading.


Solution

  • Close the stream after writing to stream in client program br.close();

    After Writing to stream it is compulsory to close the stream or flush the stream(br.flush()) because when stream is closed then only that stream can be read. I/O operations can not be performed on same stream simultaneously.

    Two sockets are connected by same stream so I/O operations can not be performed simultaneously on that stream.