Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

Please add some debug statement to check

(1) is client able to make the connection with running server or not. so in server part add

Socket s=ss.accept();
System.out.println("one new connection");

(2) also in client program add flush() after the br.write line

 br.write("\nHello World\n");
 br.flush()

 // use the below statement as well at last (if you no longer want to use the output stream)
 br.close();

Please note you are just write one time here.... for continuous reading and writing you will have to run this in loop.... OR to run multiple clients simultaneously ... you will have to execute each socket connection (after accepting it) into different thread at server end

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top