Java socket streams messing up

iv wrote a games server and it uses java socket streams to send the messages back and forth between the game clients and the game server it self
this all works great but when running and over about 5min its send over 1000 packets BUT
it will crash iv found the reason is down to when reading the packets my parser is reading wrong part and grabbing a String part when it should be a INT
now it should NEVER be reading this part of the packet so i put a trace on the packets coming in and ran it every packet was been read in perfect THEN just befor the crash TWO packets were merged together stright out from the socket stream this is y my packet reader was getting confused
what im asking is can this happen in java sockets ? i thought they were bufferered so no matter how fast you send data it would always read it out in the same order ?? not sure how its merging these to packets
is this possible of is my reader got an error in it altho works 95% of the time ??

or do you have multiple buffered streams created from the same socket?

Similar Messages

  • Socket AS3 ( Receive File .TXT ) + Java Socket

    Hi,
    I have Java Socket sending .TXT file ( 10 MB ) . But the AS3 only gets 63 Kb . I do not understand the loss of bytes ...
    Souce Java :
    public void sendFile(String fileName) {
            try {
                //handle file read
                File myFile = new File(fileName);
                byte[] mybytearray = new byte[(int) myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);
                OutputStream os = clientSocket.getOutputStream();
                byte[] fileSize = intToByte(mybytearray.length);
                byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
                System.arraycopy(fileSize, 0, clientData, 0, fileSize.length); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
                System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
                DataOutputStream dos = new DataOutputStream(os);
                //dos.writeUTF(myFile.getName());
                //dos.writeInt(mybytearray.length);
                dos.write(clientData, 0, clientData.length);
                dos.flush();
    AS3 Source..
    private function onResponse(e:ProgressEvent):void {
      var file:File;
      var fs:FileStream;
      var fileData:ByteArray = new ByteArray();
      file = File.documentsDirectory.resolvePath("tmpReceive.txt");
      fs = new FileStream();
      fs.addEventListener(Event.CLOSE,onCloseFileReceive);
    if(_socket.bytesAvailable > 0) {
      while(_socket.bytesAvailable) {
      // read the socket data into the fileData
      _socket.readBytes(fileData,0,0);
      fs.open(file, FileMode.WRITE);
      // Writing the file
      fs.writeBytes(fileData);
      fs.close();

    Crypto streams, like CipherInputStream andCipherOutputStream, do not behave properly until you
    issue a close() call. So if you are going to do
    crypto, you will need to trap the close() before it
    reaches the underlying socket streams. This is
    because the close() method finalizes the cryptographic
    operation. (Flush() would make more sense, no idea
    why they did it this way). You do want to finalize
    the crypto for any given message, but you need to trap
    the close() before it hits the socket and ends the
    whole affair.
    I don't see anything about that in the bug database.
    No matter what streams you are using, if you aregoing to keep the socket open for multiple
    request-response round-trips, you need to very closely
    pay attention to how much data is being sent on each
    trip. Normally, you can fudge this a bit on a
    request-response because the close() call on the
    output stream will cause the receiving input stream to
    behave more or less properly. However, a flush() will
    not.Why not? I use that all the time with no problem.
    A good practice is to send the content-length of
    the message first, so the receiving input stream
    "knows" when to stop reading, does not block, and then
    can send its own bytes back the other direction.
    (Where the process is repeated).
    An alternative is to use two threads: read and write.
    The read recieves, parses, validates and then pushes complete messages to a queue.
    The write pulls messages from the queue, processes and send a result.
    A variation to the above is what happens when an invalid message is received. The server can ignore it, the read can send a error response, or the read can push a message to the queue which causes the write to send a error response.

  • Connecting to http web site using java socket

    Hi,
    Sockets in Java I believe are reusable. Once created, it can be used to send a request using its input stream and get back a response using the output stream. My problem is I am trying to connect to a website using java socket but I am unable to get a response (though the same works fine I use URL and URLConnection). Can anyone tell me whats wrong? Below is the client program:
    public class HttpAdapterTest {
         public static void main(String[] args) {
              try {
                   Socket socket = new Socket("www.google.com", 80);
                   BufferedWriter out = new BufferedWriter(
                                  new OutputStreamWriter(socket.getOutputStream()));
                   out.write("GET /help/basics.html HTTP/1.1");
                   out.flush();
                   BufferedReader in = new BufferedReader(
                                            new InputStreamReader(ucon.getInputStream()));
                   String line = null;
                   while((line = in.readLine()) != null) {
                        System.out.println(line);
                   in.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Look at the JSSE examples. You need to setup a key store, add the jsse jars to your classpath, yadda, yadda, yadda....

  • Using plain Java Sockets(not RMI) how..?

    hi!
    1. Using plain Java Sockets(not RMI) how can the client detect when its server
    goes down?
    There is a long time interval between client requests and the client wants
    to retain a live connection rather than disconnect after every reqest.
    Please also cc your reply to [email protected]
    Thanks,
    \Raghu

    If you try to send data when the host is gone, it throws an exception. I don'thow to check if it is alive though. I'm having the same problem right now.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • Problem trying to read an SSL server socket stream using readByte().

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • Corrupted java.io.stream.CorruptedException in servlet

    I am getting
    Corrupted java.io.stream.CorruptedException in servlet
    while reading data from JApplet.
    The error description is
    Caught EOF Exeption while reading the streamheader.
    Kindly let me know if anybody has got a solution to this.
    regards

    are you passing serialized objects through the i/o stream? If you're code is sending serialized objects they may be reconstructed incorrectly by the recipiant. When reading the input stream, its likely your JAplet is misinterpreting the object it recieves, resulting in a 'corrupted' exception. If this is the case, make sure your JAplet is constructing the correct type of object from its input.
    not much help really, but better than nothing I guess.
    rob

  • Problems reading  an SSL server socket stream using readByte()

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • JAVA SOCKET TIMEOUT WHEN GENERATING PDF TO ADS SERVER

    We are currently getting the error when attempting to generate the PDF from the thin portal BI Reports and recieved the JAVA SOCKET READ TIME OUT error and
    applied adjustments to the notes
    934725 and 826419 by changing the timeout sessions to 300, but still get the same timeout errors:
    Note: We changed ADUSER user type and password, passed rpcData test, RFC HTTP external connections to ADS server...so we've came a long ways and here we are now with the timeout errors...
    Any ideals???

    Hi
    when you reset password please select checkbox for password never expires.
    see the following notes :
    1.Note 944221 - Troubleshooting if problems occur in forms processing
    2.Note 811342 - Time Out exception when rendering to Adobe document service
    thanks
    Gopal

  • The service bit "write enable" in Java Socket

    Hello,
    I am trying to communicate with a third party application and I am having some problems. I use a standard Socket connection, were my application is the Server (ServerSocket). The connection is established, but no data is transmitted.
    I talked with the guys behind this third party application, and they said that perhaps their application does not receive a "write enable" service bit of the tcp/ip protocol. I'm not a network wiz, so this is an unknown territory for me.
    So I ask you. What is this "write enable" tcp/ip service bit? Is this per default on in java socket connections? If no, how can I change this?
    Perhaps this is very basic knowledge, but I've googled a bit and have not found this "service bit".

    This could refer to something in their
    protocol which you aren't implementing correctly.Probably, but I believe they have "forgotten" to mention that it is required in our implementation.
    OTOH if you are the server the transaction would
    normally begin with a request from the client, not a
    write-enablement from the server.The defined protocol smelled fishy when reading the "whitepaper", but we had to accept it (politics).

  • Java sockets (peek functionality)

    Hi,
    how do i peek at a datagram, look into the data and accordingly
    decide whether to consume that datagram or leave it for later
    processing?
    Is this something Java sockets readily support OR do I need
    to implement some kind of store-for-later-processing
    please help
    Thanks.

    java.net.DatagramSocket doesn't have peek support in the API at this time - see 4102648.
    If you were to use a non-blocking DatagramChannel and register it with a Selector then you should be notification that a packet can be read. Okay, it doesn't give you the details - just that a packet is available but it may help in your environment.

  • Java sockets forwarding (redirect)

    Dear all
    I’m try to write a java sockets program which will accept VNC connection and forward it to another pc that has VNC server installed.
    That is: a client use vnc viewer connect to a JavaServer(where the sockets program run), the JavaServer accept this connection and forward it to the VNC server
    The reason doing this is because the client can only connect to the JavaServer, and the JavaServer has the ability to connect any host.
    I can manage to initiate the connection, and give the password that the VNC server request with the following code, but after this just before the viewer start to show the remote desktop, the sockets stuck on reading.
    can anyone help me out please.
    public void listen() throws Exception
    ServerSocket server=new ServerSocket(443, 5);
    System.out.println("Start Listen ...");
    while(true)
    Socket serverCon=server.accept();
    System.out.println("get Connection from: "+serverCon.getInetAddress());
    InputStream serverIn=serverCon.getInputStream();
    OutputStream serverOut=serverCon.getOutputStream();
    Socket targetCon=new Socket("192.168.1.3", 5900);
    InputStream targetIn=targetCon.getInputStream();
    OutputStream targetOut=targetCon.getOutputStream();
    byte[] buf=new byte[10240];
    int len;
    while(true)
    len=targetIn.read(buf);
    System.out.println(len);
    serverOut.write(buf, 0, len);
    len=serverIn.read(buf);
    System.out.println(len);
    targetOut.write(buf, 0, len);
    }

    Hi EJP
    Thanks for your reply,
    I did try to use threads with pipeStream,
    but it’s worse than the simple one,
    since it cannot even initiate connect between two side,
    the following is the sample code I use, which I leaned from here http://home.tiscali.nl/bmc88/java/sbook/029.html
    I can't found any more info regard to this topic on the internet, can you give me a hint.
    thanks a lot.
    public void listen2() throws Exception
      ServerSocket server=new ServerSocket(443, 5);
      System.out.println("Start Listen ...");
      while(true)
       Socket serverCon=server.accept();
       System.out.println("get Connection from: "+serverCon.getInetAddress());
       InputStream serverIn=serverCon.getInputStream();
       OutputStream serverOut=serverCon.getOutputStream();
       Socket targetCon=new Socket("192.168.1.1", 5900);
       InputStream targetIn=targetCon.getInputStream();
       OutputStream targetOut=targetCon.getOutputStream();
       PipedInputStream serverPin=new PipedInputStream();
       PipedOutputStream serverPout=new PipedOutputStream(serverPin);
       PipedInputStream targetPin=new PipedInputStream();
       PipedOutputStream targetPout=new PipedOutputStream(targetPin);
       while(true)
        ReadThread rt=new ReadThread("reader", targetIn, serverPout);
        ReadThread wt=new ReadThread("writer", serverPin, serverOut);
        ReadThread rt2=new ReadThread("reader", serverIn, targetPout);
        ReadThread wt2=new ReadThread("writer", targetPin, targetOut);
        rt.start();
        wt.start();
        rt2.start();
        wt2.start();
    class ReadThread extends Thread implements Runnable{
      InputStream pi=null;
      OutputStream po=null;
      String process=null;
      ReadThread(String process, InputStream pi, OutputStream po)
       this.pi=pi;
       this.po=po;
       this.process=process;
      public void run()
       byte[] buffer=new byte[1024];
       int bytes_read;
       try
        for(; ; )
         bytes_read=pi.read(buffer);
         if(bytes_read==-1)
          return;
         po.write(buffer, 0, bytes_read);
       catch(Exception e)
        e.printStackTrace();
    }

  • C# socket and java socket

    hello
    i am a java programmer,recently we got a project,that need the c# app to communicate with java app ,i select the socket as intermediate.
    i notice that java socket term is divided into " blocking" and "non-blocking",the latter come from jdk1.4, the c# socket is devided into "synchronized" and "asynchronized" and both of them are blocking,
    in my project,i have tried synchronized c# socket coorperating to blocking java socket,it works well..but when i modify the c# app to ASYNCHRONIZED socket,my system DON'T works well,i don't know why? i can't find asynchronized socket in java,.i learn that nio socket is nonblocking, is it asynchronized?
    who can tell me what's is the best solution for the socket communication between java and c#?

    yes,i have read them,but it only tell me the communication between java apps,and DON'T tell me any clue about c# socket.

  • Java Sockets - help with using objects

    I am new to java sockets, and need to come up with a way to send a user defined instance of a class across a basic client/server application.
    I can not find out how to do this. I read the tutorials, but my class can not be serialized. How can I send/recieve this instance of a user defined class?

    right off the top of my head, doesn't serialver just spit out a UID for a given set of classes?
    To mark a class as Serializable, just implement the java.io.Serializable class - then you could use the readObject/writeObject methods of the ObjectInputStream/ObjectOutputStream classes.
    Good luck
    Lee

  • Looking for some help on Java IO Streams

    Need to find a example or how to on:
    Java IO Streams
    using a scanner to find files with
    FileInputSeteam ...("c:\\data.in")
    did that make sense
    sandyR

    What about the API page for Scanner: http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
    And the IO tutorial: http://java.sun.com/docs/books/tutorial/essential/io/index.html (which also discusses Scanner).

Maybe you are looking for

  • Error while installing SOLUTION MANAGER 7.0 EHP 1

    Hi Experts. I face this problem while installing SOLMAN 7.0 EHP1 for MAXDB on Windows 2003 . DO you have any idea what happens with my installation?* *(Before installing this, I have more than 80GB hard disk and 4Gb RAM on Server)*An error occurred w

  • Phenom II x2 545 on K9N6PGM2-V,success!

    Got a great deal on this Callisto cpu,it's not on the supported cpu list for this motherboard,so took a chance and upgraded my Athlon 64 x2 5200 Brisbane.I have bios version 9.5 (7309v95).Been running smoothly for the last week,no hiccups or glitches

  • ITunes with files on a server, but after reboot, all files have "!" by them

    I have a MacBook Pro with iTunes that has "stuff" on it from my networked home server, and when I reboot it, all of the music, movies and TV shows ave the "!" next to them. Then, I have to delete all of the music, movies and TV shows, and reload them

  • Acs 4.2.1.15 and ssh authentication with ios xr

    Hello, we have a new acs appliance (1113) with version 4.2.1.15 and we want to authenticate user through ssh from routers with ios xr software. unfortunately this doesn't work. Here ist our configuration of the router: line template VTY access-class

  • Index sort order with underscore (_)

    Hi.  According to the documentation, the default sort order for indexes is <$symbols><$numbers><$alphabetics> with hyphens, nonbreaking hyphens, en dashes, and em dashes ignored by default.  Nothing about underscores, so they should be sorted on firs