need help writing this code in java ****************************************** P
ID: 3844559 • Letter: N
Question
need help writing this code in java
******************************************
Please do the following:
Provide a working Java program that:
creates a ServerSocket object bound to TCP port 9786
sets a time out of 10 seconds
prints to standard out "Connection established" when a connection is established
takes any text received over the socket and echoes it back to the client as well as sends a message to standard output of the form "Echo message: [text]"
prints to standard out "Timeout expired" when the time out expires
Include descriptive comments where appropriate to explain what is happening at a high level
To receive full credit, your code must properly compile and then run with these two commands (assuming a Java 7 environment):
javac SocketListener.java
java -cp . SocketListener
Explanation / Answer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public category Server
personal static Socket socket;
public static void main(String[] args)
consumer
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String range = br.readLine();
System.out.println("Message received from consumer is "+number);
//Multiplying the amount by a pair of and forming the come back message
String returnMessage;
try
number.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + " ";
}
catch(NumberFormatException e)
wasn't variety. causation correct message back to consumer.
returnMessage = "Please send a correct number ";
}
//Sending the response back to the consumer.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter warfare = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the consumer is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
finally
catch(Exception e)
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public category consumer
non-public static Socket socket;
public static void main(String args[])
finally
catch(Exception e)
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.