Transmitting Integers in Java Socket Programming

Status
Not open for further replies.
Ok, this is kinda of from my previous post, but I'll explain better. I need to transmit a integer from a client to a server, so the server can add the the number to itself subtracting one each time. I send the data to the server in the form of a string. I'm having a problem receiving the string. What's the best way to receive the data in the client. The current way I'm doing so is to use a byte array. This presents a problem though because the array can't properly interpret the length of the string that I send over. I can't define the length of the array because I don't know how long the integer is that is being sent over. How can I get the server to properly accept a string or an integer. Below is the server code.

code:<HR>
Code:
//AdditionServer.java
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;<P>
public class AdditionServer{
    public static void main(String args[]) throws IOException{
	int port=4455;
        ServerSocket server=new ServerSocket(port);<P>        while(true){
	System.out.println("Waiting for client...");
        Socket client=server.accept();
	InputStream in=client.getInputStream();<P>
        // This reads in the user selected integer and converts it to an integer<P>        // THIS IS WHERE THE ISSUE IS REAGARDING THE READ IN
        byte a[] = new byte[1];
	int num = in.read(a);
	String data=new String(a);
	System.out.println("Server received(data):" + data + "End of data");
	int number = new Integer(data).intValue();
	//System.out.println("Integer " + number);<P>
        // This is the process where the integer is added
        int total = 0;
        while (number > 0){
          total = number + total;
          number--;
        }
        //System.out.println("Total = " + total);<P>        //This is where the server sends the result back to the client
        OutputStream out=client.getOutputStream();
        String result = new Integer(total).toString();
	byte b[]=result.toString().getBytes();
        out.write(b);<P>	}
    }
}

Any help is greatly appreciated on this.

Thanks
 
This worked for me

code:<HR>
Code:
import java.io.*;<P>public class test {
	
	public static void main(String args[]) {
		try {
			byte[] b = new byte[100];
			System.out.print("Enter Integer: ");
			int len = System.in.read(b); 
			String str = new String(b, 0, (len - 2));
			int output = new Integer(str).intValue();
			System.out.println(output);
		} catch (IOException e ) {
			System.exit(-1);
		}	
	}<P>}

Hope this helps =)
P.S. Don't know why the length keeps returning 2 plus the length of the array.
 
Status
Not open for further replies.