Mohammad
Mohammad

Reputation: 3547

server/client chat socket in java

I have a server/client socket connection, each side can send a message to the other. The client who must begin the chat. I want to close the connection when one of the both sides (server and client) sends "quit" message. here is my code:

import java.io.*; 
import java.net.*; 
class TCPClient { 

    public static void main(String argv[]) throws Exception 
    { 
        String sentence; 
        String modifiedSentence; 
while(true){
        BufferedReader inFromUser = 
          new BufferedReader(new InputStreamReader(System.in)); 

        Socket clientSocket = new Socket("localhost", 6789); 

        DataOutputStream outToServer = 
          new DataOutputStream(clientSocket.getOutputStream());


        BufferedReader inFromServer =
          new BufferedReader(new
          InputStreamReader(clientSocket.getInputStream()));

        sentence = inFromUser.readLine();

        outToServer.writeBytes(sentence + '\n');

        modifiedSentence = inFromServer.readLine();

        System.out.println("FROM SERVER: " + modifiedSentence);

        if(modifiedSentence.equals("quit\n")) clientSocket.close();

}
    }
}


import java.io.*; 
import java.net.*; 

class TCPServer { 

  public static void main(String argv[]) throws Exception 
    { 
      String clientSentence; 
      String sentence; 

    BufferedReader inFromUser = 
          new BufferedReader(new InputStreamReader(System.in));

      ServerSocket welcomeSocket = new ServerSocket(6789); 

      while(true) { 

            Socket connectionSocket = welcomeSocket.accept(); 

           BufferedReader inFromClient = 
              new BufferedReader(new
              InputStreamReader(connectionSocket.getInputStream()));




           DataOutputStream outToClient =
             new DataOutputStream(connectionSocket.getOutputStream());

           clientSentence = inFromClient.readLine();
System.out.println("FROM CLIENT: " + clientSentence);

           //capitalizedSentence = clientSentence.toUpperCase() + '\n';
           sentence = inFromUser.readLine();
           outToClient.writeBytes(sentence);
       }
   }
}

Any help? :)

Upvotes: 1

Views: 1828

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533510

You have already written one line. Write another for "quit" and check this string when reading and close().

if you don't understand what you program is doing, use your debugger, that is what it is for.

Upvotes: 1

Related Questions