Deepanshu J bedi
Deepanshu J bedi

Reputation: 1530

Client connects but cant send message to the server.[Console Chat]

I tried to make a console chat server. the main problem i am facing is that i can not send the message to the server.. as you can see in the img i uploaded that the server and the client are connected. but when i type anything in the client side. The client becomes unresponsive and i have to close the cmd prompt. How can i fix this?my console chat

Is something wrong with my computer or is the code wrong?

public class MyClient 
    {
    Socket s ;

    DataInputStream din ;
    DataOutputStream dout;


    public MyClient()
    {
    try
    {
    s= new Socket("localhost",10);

    System.out.println(s);
    din = new DataInputStream(s.getInputStream());

    dout= new DataOutputStream(s.getOutputStream());

    ClientChat();

    }
    catch(Exception e)
    {
    System.err.println(e);
    }
    }

    public void ClientChat() throws IOException
    {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    //Scanner s2 = new Scanner(System.in);
    String s1;
    System.out.println("start the conversation");
    do
    {
    s1=br.readLine();
    //s1=s2.nextLine();

    dout.flush();
    System.out.println("server:"+din.readUTF());
    }
    while(!s1.equals("stop"));
    }


    public static void main (String args[])
    {
    new MyClient();
    }

    }

Upvotes: 1

Views: 700

Answers (3)

Deepanshu J bedi
Deepanshu J bedi

Reputation: 1530

Use dout.writeUTF(s1); inside the do loop. The writeUTF will allow you to write the subsequent message till then It will be stuck at readutf function.

The java.io.DataOuputStream.writeUTF(String str) method writes a string to the underlying output stream using modified UTF-8 encoding. Refer to this

Upvotes: 0

Jeff-Inventor ChromeOS
Jeff-Inventor ChromeOS

Reputation: 295

  1. The code snippet never calls dout.write*(), so nothing is ever sent over the Socket.
  2. readLine() will block until a line of text is read, so messages sent to the client won't be printed until after the client types a 2nd line of text. You can fix this either by using asynchronous I/O or by moving the read loop into it's own Thread.

Upvotes: 2

Ker p pag
Ker p pag

Reputation: 1588

You need to make the server and client a thread, so they can work independently.

server as thread will wait for a client connections and will receive messages.

client as thread will work on its own.

problem is that they cannot run concurrently.

Upvotes: 0

Related Questions