Send server max integer - java

Connects to a local server at port 3333, receives a line of integers from the Server, then finds the maximum number of integers and sends that value to the server. I'm placing all values from the line of integers into an arraylist, going through and finding the max; however, when I'm printing to the server, I get a BindException and my test fails.
public static void main(String[] args) {
try {
ArrayList<Integer> val = new ArrayList<Integer>();
// contact the server
Socket socket = new Socket("localhost", 3333);
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter writer = new PrintWriter(socket.getOutputStream(),
true);
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
val.add(num);
}
int max = val.get(0);
for (int i = 1; i < val.size(); i++) {
if (val.get(i) > max) {
max = val.get(i);
}
}
writer.println(max);
scanner.close();
writer.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

Related

Java - Client/Server Program Trying to convert int to String to get Fibonacci results

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();
}
}
}
If you want to send data between client and server as text, then what you need to do on the server side (after reading from input into byte[]) is to convert it into String and then parse as int.
That you can do with int number = Integer.parseInt(new String(data));.
However, your code has one more bug (in both client and server).
It's in the code that is writing string into the output stream.
Your code is doing following thing:
output.write(userString.length());
output.write(userString.getBytes());
which may give invalid results. Notice that length() returns length of the String, which means: number of characters.
However what you need is number of bytes. Those two values will be different in case your string contains characters from outside of ascii range.

Simple TCP client/server program in Java

Hi I'm having a small problem with my program which is a simple client/server. The client sends the contents of a textfile to the server. The text file is just ints and then the server is suppose to send back the largest prime number less than each int in the text file(if its prime it should just send back the prime number and do nothing). So for instance lets say the text file is 5 15 28. The result after running the program should be 5 13 23.
Here's my code for the Client side:
public class TCPClient {
public static void main(String[] args) throws Exception{
try{
Socket mySock = new Socket("127.0.0.1", 12001);
BufferedReader in = new BufferedReader(
new InputStreamReader(mySock.getInputStream()));
PrintStream out = new PrintStream( mySock.getOutputStream());
Scanner scan = new Scanner(new File(args[0]));
String msg = scan.nextLine();
out.println(msg);
System.out.println(in.readLine());
mySock.close();
}catch (Exception e){
}
}
}
Here's my code for the server side:
public class TCPServer {
public static void main(String[] args) throws Exception {
try{
ServerSocket mySock = new ServerSocket(12001);
Socket client = mySock.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream( client.getOutputStream());
String[] arr = in.readLine().split(" ");
int[] intarr = new int[arr.length];
for(int i = 0; i <arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
if (prim(intarr[i]) == true){
out.println(intarr[i]);
}else{
while (!prim(--intarr[i])){
}
out.println(intarr[i]);
}
}
client.close();
mySock.close();
}catch (Exception e){
}
}
public static boolean prim(int m){
int n=m;
for(int i=2;i<n;i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
When I run this program my output is only the first number in the text file. So if my text file is 1 3 5. My output is just 1. However, my prime algorithm is at least working because if my text file is 8 for instance, my program will return 7. Does anyone know why this is happening?
By change your server code to a simple test and printing to System.out
String[] arr = "1 3 5 6".split(" ");
int[] intarr = new int[arr.length];
for(int i = 0; i <arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
if (prim(intarr[i]) == true){
System.out.println(intarr[i]);
}else{
while (!prim(--intarr[i])){
}
System.out.println(intarr[i]);
}
}
you can see that it works OK, but in your code, your output in writing using println, so your client needs to loop System.out.println(in.readLine()); or change your server to write using one line and some delimiter
In TCPServer, when printing to outputstream use print instead of println
for(int i = 0; i <arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
if (prim(intarr[i]) == true){
out.print(intarr[i]); // use print instead of println
}else{
while (!prim(--intarr[i])){
}
out.print(intarr[i]); // use print instead of println
}
}

send large int[] array from java android client, to c# server

I've sent a string and images from Java Android to a C# server. But I'm having a problem with the integer array.
Is it a good logic to use dataOutputStream.writeByte(Array[i]) inside a for loop (Client side)?
I've tested with a small array of 6 elements only. In the server, the array elements are received but not the same numbers as in client array. Why is that?
OUTPUT:
client array : (1,3333,50,6,7,8}
server array : {37, 37, 9, 45, 18, 18}!!
Client Android:
public void ConnectToServer()
{
//generate array with random numbers
int[] array = {1,333,5,60,7,8};
try {
//Connect to socket
Socket socket = new Socket(HOST, PORT);
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
for(int i=0; i< 6; i++)
{ outToServer.writeByte(array[i]);}
outToServer.flush();
socket.shutdownOutput();
Log.e("MESSAGE", "array sent Successfully");
//receive msg from (server)
BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream())); //for reading response from server
recievedMsg = r.readLine();
//clean
r.close();
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Server:
static void Main(string[] args)
{
try
{
IPAddress ipAdress = IPAddress.Parse("192.168.10.3");client
TcpListener listener = new TcpListener(ipAdress, 4003);
listener.Start();
Console.WriteLine("Server Waiting for connections...");
Socket s = listener.AcceptSocket();
// When accepted
NetworkStream nstm = new NetworkStream(s);
BinaryReader reader = new BinaryReader(nstm);
byte result;
int number;
for (int i = 0; i < 6; i++)
{ result = reader.ReadByte();
number = Convert.ToInt32(result);
Console.WriteLine(number.ToString() + "---"+ i);
}
//send the response to client
Byte[] sendData = Encoding.ASCII.GetBytes("received !");
nstm.Write(sendData, 0, sendData.Length);
//Clean up
s.Close();
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error.....CL1 " + e.Message + e.StackTrace);
}
}
java use big endian, and c# use little endian.

Java beginner (Client-Server) : Sending multiple Integers to a socket

i have a very simple assignment in which i am supposed to send 2 integers into a socket, which sends their sum back to the "client".
this is my client:
int a,b,sum;
try
{
Socket Server_info = new Socket ("localhost", 15000);
BufferedReader FromServer = new BufferedReader (new InputStreamReader(Server_info.getInputStream()));
DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
while (true)
{
System.out.println("Type in '0' at any point to quit");
System.out.println("Please input a number");
a = User_in.nextInt();
ToServer.writeInt(a);
System.out.println("Please input a second number");
b = User_in.nextInt();
ToServer.writeInt(b);
sum = FromServer.read();
System.out.println("the sum of " +a+ " and " +b+ " is: " +sum );
if (a==0 || b==0)
break;
}
this is my socket handler:
int num1=0 ,num2=0, sum;
try
{
BufferedReader InFromClient = new BufferedReader (new InputStreamReader(soc_1.getInputStream()));
DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
while (true)
{
num1 = InFromClient.read();
num2 = InFromClient.read();
sum = num1 + num2 ;
OutToClient.writeInt(sum);
}
}
catch (Exception E){}
After the first Integer input upon running the client i get this:
Type in '0' at any point to quit
Please input a number
5
Connection reset by peer: socket write error
i think the problem lays at the socket receiving side, i must be doing something wrong. any suggestions?
You can use DataInputStream and DataOupStream objects but I find it simpler to user a pair of Scanner and PrintWriter objects both at the server side and client side. So here is my implementation of the solution to the problem:
The Server Side
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoServer {
private static ServerSocket serverSocket;
private static final int PORT = 1234;
public static void main(String[] args)
{
System.out.println("Opening port...\n");
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException ioex){
System.out.println("Unable to attach to port!");
System.exit(1);
}
handleClient();
}
private static void handleClient()
{
Socket link = null; //Step 2
try {
link = serverSocket.accept(); //Step 2
//Step 3
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
int firstInt = input.nextInt();
int secondInt = input.nextInt();
int answer;
while (firstInt != 0 || secondInt != 0)
{
answer = firstInt + secondInt;
output.println(answer); //Server returns the sum here 4
firstInt = input.nextInt();
secondInt = input.nextInt();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
System.out.println("Closing connection...");
link.close();
}
catch (IOException ie)
{
System.out.println("Unable to close connection");
System.exit(1);
}
}
}
}
The Client Side
import java.net.*;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class TCPEchoClient {
private static InetAddress host;
private static final int PORT = 1234;
public static void main(String[] args) {
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException uhEx) {
System.out.println("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer() {
Socket link = null; //Step 1
try {
link = new Socket(host, PORT); //Step 1
//Step 2
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter(link.getOutputStream(), true);
//Set up stream for keyboard entry
Scanner userEntry = new Scanner(System.in);
int firstInt, secondInt, answer;
do {
System.out.print("Please input the first number: ");
firstInt = userEntry.nextInt();
System.out.print("Please input the second number: ");
secondInt = userEntry.nextInt();
//send the numbers
output.println(firstInt);
output.println(secondInt);
answer = input.nextInt(); //getting the answer from the server
System.out.println("\nSERVER> " + answer);
} while (firstInt != 0 || secondInt != 0);
} catch (IOException e) {
e.printStackTrace();
}
catch (NoSuchElementException ne){ //This exception may be raised when the server closes connection
System.out.println("Connection closed");
}
finally {
try {
System.out.println("\n* Closing connection… *");
link.close(); //Step 4.
} catch (IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
The problem is that you mix streams and readers.
In order to successfully pass integers from client to server, for example with Data[Input/Output]Stream you should use:
// Server side
final DataInputStream InFromClient = new DataInputStream(soc_1.getInputStream());
final DataOutputStream OutToClient = new DataOutputStream(soc_1.getOutputStream());
// than use OutToClient.writeInt() and InFromClient.readInt()
// Client side
final DataInputStream FromServer = new DataInputStream(Server_info.getInputStream());
final DataOutputStream ToServer = new DataOutputStream(Server_info.getOutputStream());
// than use ToServer.writeInt() and FromServer.readInt()
If you let's say send an int from client to server (in this case using DataOutputStream.writeInt), it is very important to read the data with the corresponding decoding logic (in our case DataInputStream.readInt).

NoSuchElementFoundException While Receiving Data from Server

public class cli
{
public static void main(String args[]) throws IOException
{
int no,rec;
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1400);
Scanner sc1 = new Scanner(s.getInputStream());
System.out.println("Enter any number");
no = sc.nextInt();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(no);
rec = sc1.nextInt();
System.out.println("Receive number is " + rec);
}
}
I am sending a number to server and getting a number that is multiple of the number sent, but the problem I am facing is here: the rec=sc1.nextInt() statement gives me NoSuchElementFoundException. What am I doing wrong? Thanks.
Server code:
public class Server {
public static void main(String args[]) throws IOException {
ServerSocket ss = new ServerSocket(1400);
System.out.println("Waiting ");
Socket s1 = ss.accept();
Scanner sc = new Scanner(s1.getInputStream());
int a = sc.nextInt();
int temp = 2 * a;
PrintWriter ps = new PrintWriter(s1.getOutputStream());
ps.write(temp);
ps.flush();
System.out.println("Got and sent Sucessfull " + temp);
ss.close();
}
}
The problem is that you are not writing a number to the server's output, but a character with the 2*a code.
int temp = 2 * a;
PrintWriter ps = new PrintWriter(s1.getOutputStream());
ps.write(temp);
Here invoking write(temp) writes the character with the temp code to the output. For example, if a was 16, then temp is 32, so writing this to the PrintWriter actually writes a space character. If you want to write the number as a string, do this:
ps.write(Integer.toString(temp));

Categories