Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q1 : Modify the programs to create a chat between the server and the client. The

ID: 3823511 • Letter: Q

Question

Q1 : Modify the programs to create a chat between the server and the client. The client send a text to the server, the server will print in and sends an answer to the client. Use a loop to repeat the task.

import java.io.*;

import java.net.*;

import java.util.Scanner;

public class Server{

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

/*1.connection*/

ServerSocket serverSocket = new ServerSocket(6789);

Socket connectionSocket = serverSocket.accept();

/*2. reading from the socket using scanner or BufferedReader*/

Scanner scanner = new Scanner(connectionSocket.getInputStream());

//read

String clientSentence = scanner.nextLine();

System.out.println("Received: " + clientSentence);

/*3. modification of the sentence*/

String modifiedSentence =clientSentence.toUpperCase();

/*4. writing in the socket*/

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

outToClient.writeBytes(modifiedSentence+ ' ');

scanner.close();

connectionSocket.close();

}

}

Explanation / Answer

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server{
public static void main(String argv[]) throws Exception {
/*1.connection*/

ServerSocket serverSocket = new ServerSocket(6789);
Socket connectionSocket = serverSocket.accept();
/*2. reading from the socket using scanner or BufferedReader*/
Scanner scanner = new Scanner(connectionSocket.getInputStream());
//read


while(scanner.nextLine != null){

String clientSentence = scanner.nextLine();
invokeConnection(clientSentence,connectionSocket );

}

scanner.close();
connectionSocket.close();
}


private String invokeConnection(String str, Socket connectSocket)
{

System.out.println("Received: " + str);

String modifiedSentence =str.toUpperCase();

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
outToClient.writeBytes(modifiedSentence+ ' ');


}

}