Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Sending integers through a socket

  1. #1
    Junior Member
    Join Date
    Aug 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Sending integers through a socket

    Oh hai guise.

    So I don't really know a lot of java,but I've been trying to make a server for my flash game.
    I've been basing it heavily on the example here :How to make a multi-client Flash Java server | Broculos.net

    I remember back when I worked with GameMaker and 39dll, I could write bytes and stuff in order in a buffer, and send that buffer to multiple clients.
    I've managed to make it work sending strings, and using string manipulation, but I'm trying to get it right with sending integers and strings.

    So far I have this.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /**
     *
     * @author Fricken Hamster
     */
     
    import java.net.*;
    import java.io.*;
     
     
    public class GameServerConnection extends Thread
    {
        protected Socket socket;
        protected BufferedReader socketIn;
        protected PrintWriter socketOut;
        protected GameServer server;
        protected String clientName;
        protected int slotId;
        protected String slotIdString;
     
        public GameServerConnection( Socket socket, GameServer server)
        {
            this.socket = socket;
            this.server = server;
     
     
        }
     
        public SocketAddress getRemoteAddress()
        {
            return this.socket.getRemoteSocketAddress();
        }
     
        protected void debug( String str)
        {
            ACityMain.debug(str);
        }
     
        public void run()
        {
            try
            {
                this.socketIn = new BufferedReader( new InputStreamReader( this.socket.getInputStream()));
                this.socketOut = new PrintWriter(this.socket.getOutputStream() , true);
     
    	    this.slotIdString = Integer.toString(this.slotId);
    	    if ( slotIdString.length() < 2)
    	    {
    		slotIdString = "0" + slotIdString;
    	    }
                //this.server.writeToAll( "01" + slotIdString );
                this.server.writeToAll( 1 , this.slotId , "");
     
                //String line = this.socketIn.readLine();
     
                //System.out.println(line);
    	    int header = this.socketIn.read();
    	    System.out.print(header);
                //while( line != null )
                while (header != 0)
    	    {
                    debug("recieved from " + this.clientName + ": " + header);
     
                    //int header = Integer.parseInt(line.substring(0, 2));
    		//String body = line.substring(2,line.length());
    		//String newLine;
    		String body;
    		switch (header)
    		{
    		    case 2:
    			body = this.socketIn.readLine();
    			this.clientName = body;
    			//newLine = "02" + this.slotIdString + body;
    			//this.server.writeToAll(newLine);
    			this.server.writeToAll(header, this.slotId, body);
    			//debug("read 2");
    		    break;
     
    		    case 9:
    			if( this.server.remove(this.slotId))
    			{
    			    this.finalize();
    			    return;
    			}
    		    break;
     
    		    case 10:
     
    			//newLine = "10" + this.slotIdString + body;
    			body = this.socketIn.readLine();
    			this.server.writeToAll(header, this.slotId, body);
    			//newLine);
    		    break;
     
    		}
    		//line = this.socketIn.readLine();
     
                }
     
            }
            catch( Exception e)
            {
                debug( "Run Error:" + e.getMessage());
            }
        }
     
        public void write( int header , int id , String msg)
        {
    	try
    	{
    	    this.socketOut.write(header);
    	    this.socketOut.write(id);
    	    this.socketOut.write(msg + "\u0000");
    	    //this.socketOut.write(msg + "\u0000");
    	    this.socketOut.flush();
    	}
    	catch( Exception e)
            {
                debug( "Write Error:" + e.getMessage());
            }
        }
     
     
        protected void finalize()
        {
    	try
    	{
    	    this.socketIn.close();
    	    this.socketOut.close();
    	    this.socket.close();
    	    debug("connection closed at " + this.getRemoteAddress());
    	}
    	catch( Exception e)
            {
                debug( "Finalize Error:" + e.getMessage());
            }
        }
     
    }

    Can anyone help me, or point me towards some examples/documentation of what I neeD? Thanks!


  2. #2
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Sending integers through a socket

    I'm not sure there's enough info there for someone to be able to give you constructive advice, but PrintWriter (always read the API documentation) may be a poor choice for socketOut. From the API docs:
    It does not contain methods for writing raw bytes

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sending integers through a socket

    For testing, you could change the underlying Stream to a ByteArrayOutputStream(vs getting one from the socket) that you could then examine after you send/write some data to see what is being written to the output stream.

  4. #4
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Sending integers through a socket

    After having a quick peep at this again, I reckon your simplest way forward (least changes) is to format your ints as Strings and do string-to-int conversion in Flash. What will be happening when you write an int on a PrintWriter is that the int will be converted to a single character, and characters on the Java platform are 16-bits. While you're in the API docs, read PrintWriter.write(int) and follow the link to the method it overrides in Writer.write(int) - there's a message in there specially for you, I guess.

    If you've tested the Flash/Java chat software and it works well, I think you should go for a low-fat fix. You need a fixed-width format for your message to make decoding it easy at the client, so have a think about how big those ints can be, and then string format them at a width that will cope for the largest and smallest values. ints are 32-bit, so you may be looking at sending an 8-character hex string and decoding that in Flash.

Similar Threads

  1. Sending zip from server socket
    By moon_werewolf in forum Java Theory & Questions
    Replies: 0
    Last Post: May 30th, 2011, 07:51 AM
  2. [SOLVED] Sending xml file over a socket
    By Kakashi in forum Java Networking
    Replies: 2
    Last Post: March 9th, 2011, 09:41 AM
  3. [SOLVED] Writing Integers to .txt File; Returning Random Characters Instead of Integers
    By verbicidalmaniac in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: March 8th, 2011, 09:42 PM
  4. Replies: 2
    Last Post: February 14th, 2011, 05:36 PM
  5. Sending object through socket
    By Alexandrinne in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 16th, 2010, 02:18 AM