0

I have some problems with my server socket. I create a DatagramSocket to chat between a server and a client.

public static void main (String[] args) throws IOException {

        byte[] send = new byte[1024];
        byte[] receive = new byte[1024];
        BufferedReader entree;
        DatagramSocket serverSocket = null;
        InetAddress ip;
        InetAddress ipDest;
        int port;

        try {
            serverSocket = new DatagramSocket(8888);
        } catch (SocketException e) {
            e.printStackTrace();
        }

        while (true) {
            DatagramPacket recu = new DatagramPacket(receive, receive.length);
            serverSocket.receive(recu);
            String sentence = new String(recu.getData());
            ipDest = recu.getAddress();
            port = recu.getPort();
            System.out.println("Reçu:"+sentence);


            entree = new BufferedReader(new InputStreamReader(System.in));
            String chaine = entree.readLine();
            send = chaine.getBytes();
            DatagramPacket dp = new DatagramPacket(send, send.length, ipDest, port); 
            serverSocket.send(dp);

            send = new byte[1024];
            receive = new byte[1024];
        }

But I use new BufferedReader(new InputStreamReader(System.in)) get the next stuff to send, and it is blocking. So, I cannot receive what's comming from the client and print it.
How can I arrange this ?
Merci, eo

eouti
  • 5,338
  • 3
  • 34
  • 42
  • 1
    You'll have to put it on different threads if you want to be capable of both sending and receiving 'at the same time'. – Reinard Mar 26 '12 at 13:41

1 Answers1

0

Trying to do non-blocking reads on System.in in Java is an exercise in futility. There's no portable way to do it, so Java doesn't support it.

Even if you create a separate thread and do a blocking read there, you'll have the problem of that thread being non-interruptible. See: Java: how to abort a thread reading from System.in

Basically, you either need to use a platform specific library (JNI) (JCurses for linux, for example), or use a GUI.

Edit to add: What you can do is move your socket reading to a different thread, as that is interruptible.

Community
  • 1
  • 1
Brian Roach
  • 76,169
  • 12
  • 136
  • 161