I am creating a Socket Client/Sever program that outputs the results of a fibonacci formula. I have already built the client/server connection and have tested. That part of it is working as intended. I am now trying to add in the fibonacci formula to the server but am having trouble coding the conversion of int type toSring(). The fibonacci formula is running on the server side. Code will be posted below. Thank you all for the help. I am trying to pass the clients input into fibonacci(int n) to get the desired results. If the user inputs 2, the answer should be 3, since 2 + 1 = 3 in the fibonacci numbering sequence.
Server Code:
public class ServerData {
public static int fibonacci(int n) {
int v1 = 0, v2 = 1, v3 = 0;
for(int i = 2; i <= n; i++) {
v3 = v1 + v2;
v1 = v2;
v2 = v3;
}
return v3;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
boolean shutdown = false;
try {
server = new ServerSocket(1236);
System.out.println("Port bound. Accepting connection");
} catch(IOException e) {
e.printStackTrace();
System.exit(-1);
}
while(!shutdown) {
Socket client = null;
InputStream input = null;
OutputStream output = null;
try {
client = server.accept();
input = client.getInputStream();
output = client.getOutputStream();
int n = input.read();
byte[] data = new byte[n];
input.read(data);
// int fibOut = fibonacci(int n);
String clientInput = new String (data, StandardCharsets.UTF_8);
clientInput.replace("\n","");
System.out.println("Client said: " + clientInput);
String response = ("Your input was [" + clientInput + "]");
output.write(response.length());
output.write(response.getBytes());
client.close();
if(clientInput.equalsIgnoreCase("shutdown")) {
System.out.println("shutting down...");
shutdown = true;
}
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
Client Code:
public class ClientData {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Input a String: ");
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
try {
String userString = userInput.readLine();
Socket connection = new Socket("127.0.0.1", 1236);
InputStream input = connection.getInputStream();
OutputStream output = connection.getOutputStream();
output.write(userString.length());
output.write(userString.getBytes());
int n = input.read();
byte [] data = new byte[n];
input.read(data);
String serverResponse = new String(data, StandardCharsets.UTF_8);
System.out.println("Server said: " + serverResponse);
if (!connection.isClosed());
connection.close();
}
catch (IOException e ) {
e.printStackTrace();
}
}
}