Transmitting Integers in Java Socket Programming

Status
You're currently viewing only RGrizzzz's posts. Click here to go back to viewing the entire thread.
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
 
Status
You're currently viewing only RGrizzzz's posts. Click here to go back to viewing the entire thread.
Not open for further replies.