Skip to content
Snippets Groups Projects
Commit 77e00c09 authored by bweissenbergergy's avatar bweissenbergergy
Browse files

Commit TCPNumberReceiverUDPResultSender for HW #3

08/17/2020
parent c95a8ad7
No related branches found
No related tags found
No related merge requests found
package MV3500Cohort2020JulySeptember.homework3.Goericke;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This class will be connected by an TCP sender over VPN (argon), calculating
* a result of an equation and send the result back via UDP over VPN.
* @date 08/17/2020
* @group Goericke/Weissenberger
*/
public class TCPNumberReceiverUDPResultSender {
// Change this to the port where the TCP server is listening
private static final int TCP_ARGON_SERVER_PORT = 2317;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
// ServerSocket waits for a connection from a client.
System.out.println("TCPNumberReceiver has started...");
ServerSocket serverSocket = new ServerSocket(TCP_ARGON_SERVER_PORT);
InetAddress remoteAddress;
// declare the stream and readers
InputStream inputStream;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
// declare needed variables
String clientMessage;
int number1, number2;
String calculation_Method;
int iUDPResultReceivingPort;
// Server is up and waiting (i.e. "blocked" or paused)
// Loop, infinitely, waiting for client connections.
while (true) {
// block until connected to a client
try (Socket clientConnectionSocket = serverSocket.accept())
{
// Now hook everything up (i.e. set up the streams), Java style:
inputStream = clientConnectionSocket.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
// get the date from TCP packet
clientMessage = bufferedReader.readLine();
number1 = Integer.parseInt(bufferedReader.readLine());
number2 = Integer.parseInt(bufferedReader.readLine());
calculation_Method = bufferedReader.readLine();
iUDPResultReceivingPort = Integer.parseInt(bufferedReader.readLine());
// print them out (for debugging)
System.out.println("Message recived: "+clientMessage);
System.out.println("Number 1 recived: "+number1);
System.out.println("Number 2 recived: "+number2);
System.out.println("Calc Method recived: "+calculation_Method);
System.out.println("Send result to port: "+iUDPResultReceivingPort);
// get the sender IP (is used for sending UDP)
remoteAddress = clientConnectionSocket.getInetAddress();
System.out.println("Send result to IP: "+remoteAddress.getHostAddress());
// try to send the calculated result as a float via UDP...
sendResultViaUDP(calculateResult(number1, number2, calculation_Method), remoteAddress, iUDPResultReceivingPort);
}
}
} catch (IOException e) {
System.err.println("Problem with TcpExample3Server networking: " + e);
// Provide more helpful information to user if exception occurs due to running twice at one time
if (e instanceof java.net.BindException) {
System.err.println("*** Be sure to stop any other running instances of programs using this port!");
}
}
}
/**
* send the result to Bernd 10x
* @param result
* @param inetAddress Bernd's IP
* @param port Bernd's UDP port number
* @throws IOException
*/
private static void sendResultViaUDP(float result, InetAddress inetAddress, int port) throws IOException{
DatagramSocket udpSocket = null;
DataOutputStream dos = null;
try
{
// Create a UDP socket
udpSocket = new DatagramSocket(); // let system assign output port, then SENDING_PORT not needed
// Put together a message with binary content. "ByteArrayOutputStream"
// is a java.io utility that lets us put together an array of binary
// data, which we put into the UDP packet.
ByteArrayOutputStream baos = new ByteArrayOutputStream(1500); // how many bytes are in buffer? MTU=1500 is good
dos = new DataOutputStream(baos); // wrapper for writing values, connects both streams
// Put together a packet to send
// these types and order of variables must match on sender and receiver
byte[] byteArray = baos.toByteArray();
DatagramPacket datagramPacket = new DatagramPacket(byteArray, byteArray.length, inetAddress, port);
for (int index = 1; index <= 10; index++)
{
dos.writeFloat (result);
dos.flush(); // sends DataOutputStream to ByteArrayOutputStream
byteArray = baos.toByteArray(); // OK so go get the flushed result...
datagramPacket.setData(byteArray); // and put it in the packet...
udpSocket.send(datagramPacket); // and send it away. boom gone, nonblocking.
Thread.sleep(1000); // Send packets at rate of one per second
baos.reset(); // clear the output stream after sending
}
dos.close();
}
catch (IOException | InterruptedException e)
{
System.err.println("Problem with UdpSender, see exception trace:");
System.err.println(e);
}
finally // clean up prior to exit, don't want to leave behind zombies
{
if (udpSocket != null)
udpSocket.close();
if (dos != null)
dos.close();
}
}
/**
* calculates the result based on given numbers and operator
* @param n1 first number
* @param n2 second number
* @param operator
* @return the result as a float
*/
private static float calculateResult(int n1, int n2, String operator){
float result = -1;
switch (operator) {
case "+":
result = n1 + n2;
break;
case "-":
result = n1 - n2;
break;
case "*":
result = n1 * n2;
break;
case "/":
result = n1 / n2;
break;
default:
System.err.println(operator +" is not a valid operator!");
break;
}
return result;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment