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

Write a simple TCP program for a client that reads a line of text from its stand

ID: 3807084 • Letter: W

Question

Write a simple TCP program for a client that reads a line of text from its standard input (keyboard) and sends the line out its socket to the server. The server reads the line from the socket and prints it in its standard output (screen). The server then reads a line from its standard input (keyboard) and sends it out its socket to the client. When the client sends “!” the server should reply back “bye” to the client and it closes the socket.

Sample Output Client:

Client: Hi there

Server: Hello

Client: How are you?

Server: I am fine

Client: ! Server: Bye

Explanation / Answer

TCPClient.java :

import java.io.*;

import java.net.*;

class TCPClient

{

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

String sentence;

String modifiedSentence;

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

Socket clientSocket = new Socket("hostname", 1234);

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

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

sentence = inFromUser.readLine();

outToServer.writeBytes(sentence + ' ');

modifiedSentence = inFromServer.readLine();

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

clientSocket.close();

}

}

TCPServer.java :

import java.io.*;

import java.net.*;

class TCPServer {

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

{

String clientSentence;

String capitalizedSentence;

String s;

ServerSocket welcomeSocket = new ServerSocket(1234);

while(true) {

Socket connectionSocket = welcomeSocket.accept();

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

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

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() +' ';

outToClient.writeBytes(capitalizedSentence);

if (s.equalsIgnoreCase("BYE");

break;

}

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote