
Jy J.
asked 04/17/21Write a client server program using sockets.
In server a list of random thoughts are stored. Client request for a random thought. Using a random number, pick a random thought and post it to the client side.
(use c, c++ or python as programming languages)
1 Expert Answer

Patrick B. answered 04/17/21
Math and computer tutor/teacher
import java.io.*;
import java.net.*;
class ThoughtServer
{
public void Go()
{
String thoughts[] = {"thought string #1","thought string #2","thought string #3"};
int numThoughts = thoughts.length;
try
{
ServerSocket serverSocket = new ServerSocket(80);
System.out.print(" waiting for client...");
Socket socket = serverSocket.accept();
PrintStream out = new PrintStream( socket.getOutputStream() );
InputStream inputStream = socket.getInputStream();
System.out.println("Waiting for request...");
int num_bytes;
while ((num_bytes = inputStream.available())<=0) { }
byte[] inbuff = new byte[num_bytes];
inputStream.read(inbuff);
String inbuffStr = new String(inbuff);
int thoughtNum = Integer.parseInt(inbuffStr);
if ((thoughtNum>=0) && (thoughtNum<numThoughts))
{
out.println(thoughts[thoughtNum]);
}
out.close();
inputStream.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("IO Exception occurs");
}
}
public static void main(String args[])
{
(new ThoughtServer()).Go();
}
}
/*********************************************************************************************/
import java.io.*;
import java.net.*;
class ThoughtClient
{
public void Go(String argThoughtNum)
{
try
{
Socket socket = new Socket("127.0.0.1",80);
PrintStream out = new PrintStream( socket.getOutputStream() );
BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
out.print(argThoughtNum);
String inbuff = in.readLine();
System.out.println(inbuff);
out.close();
in.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("IO Exception occurs");
}
}
public static void main(String args[])
{
(new ThoughtClient()).Go(args[0]);
}
}
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Patrick B.
I am very sorry04/17/21