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
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 + '\n');
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() +'\n';
outToClient.writeBytes(capitalizedSentence);
if (s.equalsIgnoreCase("BYE");
break;
}
}
}
Get Answers For Free
Most questions answered within 1 hours.