Simple client server program not working

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 20:09:20

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/19807028/simple-client-server-program-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!