In: Computer Science
Write a Socket-based Java server program that responds to client messages as follows: When it receives a message from a client, it simply converts all the letters into ASCII characters and sends back them to the client. Write both client and server programs demonstrating this.
Server Program:
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[])
{
String inputMessage;
String outputMessage;
try {
ServerSocket ssock = new ServerSocket(6789);
while(true)
{
Socket connsock = ssock.accept();
InputStreamReader inStr = new InputStreamReader(connsock.getInputStream());
BufferedReader inNet = new BufferedReader(inStr);
DataOutputStream outNet = new DataOutputStream(connsock.getOutputStream());
inputMessage = inNet.readLine();
outputMessage = inputMessage.toUpperCase();
outNet.writeBytes(outputMessage);
}
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Client Program
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args)
{
String message = null;
try {
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
Socket csock = new Socket("localhost", 6789);
DataOutputStream outNet = new DataOutputStream(csock.getOutputStream());
BufferedReader inNet = new BufferedReader(new InputStreamReader(csock.getInputStream()));
message = kbd.readLine();
outNet.writeBytes(message + "");
message = inNet.readLine();
csock.close();
System.out.println("Server sent: " + message);
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Output:
First, run the server using the java Server command and then open the second window and run the client.
C:> java Client
How Are You
Server sent: HOW ARE YOU
Program with following output was created
C:> java Client
How Are You
Server sent: HOW ARE YOU