Results 1 to 8 of 8
  1. #1
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Java client sends a partial message to server although shows as a full message

    Hi. I have a client written in Java and a server written in C++. The client is supposed to send a message like this "MESSAGE|1|2|3|4|5" every 5 seconds upon receiving the response from server.

    Java Code:
    package testtcp;
    
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    
    
    public class TestTCP 
    {
        private Socket socket = null;
        private DataInputStream input = null;
        private DataOutputStream output = null;
        private BufferedReader br = null;
        private Timer timer;
        ScheduledExecutorService executorService;
        private boolean isMapUpdating = false;
    
    
        public static void main(String[] args) 
        {
            // Start TCP connection
            TestTCP testTCP = new TestTCP();
            testTCP.start();
        }
        
    
        public void start() 
        {
            // Default timer rate
            int timerRate = 5;
            
            try
            {
                // Create socket and streams
                socket = new Socket("192.168.1.2", 7767);
                input = new DataInputStream( socket.getInputStream());
                output = new DataOutputStream( socket.getOutputStream());
                
                // Start Timer thread
                executorService = Executors.newSingleThreadScheduledExecutor();
    
                executorService.scheduleAtFixedRate(new Runnable() 
                {
                    @Override
                    public void run() 
                    {
                        // Create new TCP connection if the map is not currently updating
                        if(isMapUpdating == false)
                        {
                            isMapUpdating = true;
    
                            communicateWithServer();
                        }
                    }
                }, 0, timerRate, TimeUnit.SECONDS);
            }
            catch (UnknownHostException e)
            {
                System.out.println("Sock:"+e.getMessage());
                cancelConnection();
            }
    
            catch (EOFException e)
            {
                System.out.println("EOF:"+e.getMessage()); 
                cancelConnection();
            }
    
            catch (IOException e)
            {
                System.out.println("IO:"+e.getMessage());
                cancelConnection();
            }
    
        }
    
        
        public void communicateWithServer()
        {
            // Create a message to the server
            String messageToServer = makeMessageToServer();
            
            System.out.println("MESSAGE TO SERVER: "+messageToServer);
                
            // Connect to the client and receive the response    
            String messageFromServer = connectToClient(messageToServer);
            
            // Read the message and update ACARS panel on the main thread
            SwingUtilities.invokeLater(() ->
            {
                messageReceived(messageFromServer);
            });
            
        }
        
        
        public String connectToClient(String messageToServer)
        {
            String data = "";
            // Message from the server that should terminate TCP connection
            String  terminator = "END_IGOCONNECT_DATA";
            
            try 
            {
                //Send message to the server
                output = new DataOutputStream( socket.getOutputStream());
                output.writeBytes(messageToServer);
                output.flush();
                
                System.out.println("OUTPUT STRING: "+output.toString());
                System.out.println("OUTPUT LENGTH: "+output.size());
                
                //Read Response
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String s = "";
                int value;
                
                // Process the message from the server and add to the StringBuilder
                while((value = br.read()) != -1) 
                {
                    // converts int to character
                    char c = (char)value;
    
                    sb.append(c);
                    
                    if(sb.toString().contains(terminator))
                    {
                        break;
                    }
                }
                
                // Create the final string
                data = sb.toString();
            } 
            catch (IOException e) 
            {
                System.out.println("Connect to client IO:"+e.getMessage());
                // Close Connection
                cancelConnection();
                
                // Pop-up message that the server was not found
                if(!e.getMessage().equals("Socket closed"))
                {
                    System.out.println("Connect to client : Socket closed"+e.getMessage());
                }
                
                data = "ERROR";
            }
    
            return data;
        }
        
        
        public void cancelConnection()
        {
            // Stop the timer
            if(executorService != null && !executorService.isShutdown())
            {
                executorService.shutdown();
            }
            
            closeSocketPax();
            
            SwingUtilities.invokeLater(() ->
            {
                
                // Map finished updating
                isMapUpdating = false;
                
                System.out.println("Connection Cancelled");
                
            });
        }
        
        
        private void closeSocketPax()
        {
            try
            {   
                if(socket!=null) { socket.close();}
                if(input != null) { input.close();}
                if(output != null) { output.close();}
                if(br != null) { br.close();}
            }
            catch (IOException ex) 
            {
                System.out.println("Error closing Socket when connecting ACARS to the Server: "+ex);
            }
            socket = null;
            input = null;
            output = null;
            br = null;
        }
        
        
        private String makeMessageToServer()
        {
    
            String cgOffsetSend = "0.12";
            
            // Get Vref speeds. Flaps positions: 1|2|5|10|15|25|30|40
            String vref1 = "N/A";
            String vref2 = "N/A";
            String vref5 = "N/A";
            String vref10 = "N/A";
            String vref15 = "N/A";
            String vref25 = "N/A";
            String vref30 = "N/A";
            String vref40 = "N/A";
    
            // Compile message
            String messageToServer  =   "IGODISPATCHBOEING733:"+cgOffsetSend+"|"
                                        +vref1+"|"+vref2+"|"+vref5+"|"+vref10+"|"
                                        +vref15+"|"+vref25+"|"+vref30+"|"+vref40;
    
            return messageToServer;
        }
        
        
        private void messageReceived(String message)
        {
            System.out.println("MESSAGE FROM SERVER: "+message);
            
            String acarsReport = message;
            
            String[] reportItems = acarsReport.split("\\|");
            
            if (reportItems.length == 11)
            {
                System.out.println("Error sending the correct message from server -- old plugin");
                // Disconnect from server
                cancelConnection();
            }
        
            else if (reportItems.length == 14)
            {
                // Identifying the type of message (ACARS vs LOAD)
                String msgType = reportItems[0];
        
                // If this is an ACARS_NEW message, this is a new reset flight. Nothing to display and reset all announcement counts
                if (msgType.equals("ACARS_NEW") )
                {
                    for(String reportItem: reportItems)
                    {
                        System.out.println("ACARS_NEW Report Item: "+reportItem);
                    }
    
                    // Map finished updating
                    isMapUpdating = false;
                }
                else if (msgType.equals("ACARS"))
                {
                    for(String reportItem: reportItems)
                    {
                        System.out.println("ACARS_RECEIVED Report Item: "+reportItem);
                    }
                    
                    // Map finished updating
                    isMapUpdating = false;
                }
                else
                {
                    System.out.println("ACARS message not determined");
                    // Disconnect from server
                    cancelConnection();
                }
            }
            else
            {
                System.out.println("Error sending the correct message from server -- array different");
                // Disconnect from server
                cancelConnection();
            }
        }
        
    }
    The server gets the message from the client, converts it to an array, and then processes the data further on. The first message is sent just fine. However, on the second message, the server crashes. I checked what is being sent to the server, and it turns out that the messages are like this:

    Java Code:
    "MESSAGE|1|2|3|4|5"
    
    "M"
    
    "ESSAGE|1|2|3|4|5"
    So, the server crashes on the second received message since it cannot split it into arrays. (Of course, I can make the server continue without crashing, but I leave it as is for now to ensure that the client works properly.)

    When I check the DataOutputStream, it always shows me the correct size. Another interesting thing to note is that it seems to be platform specific: on Mac the server gets the full message, but in Windows -- as shown above.

    If someone has an idea how to fix it, this would be much appreciated!
    Last edited by igorland; 03-13-2018 at 01:46 AM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,959
    Rep Power
    31

    Default Re: Java client sends a partial message to server although shows as a full message

    How can the code be compiled and executed for testing?
    There needs to be import statements, a class definition and a main method.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: Java client sends a partial message to server although shows as a full message

    How is the server handling the incoming message?
    Have you tried flushing the output stream?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: Java client sends a partial message to server although shows as a full message

    OK, guys. I have updated the code so that it can be compiled and tested.

    Upon receiving a message from Client, Server looks for the key word "IGODISPATCHBOEING733", splits it into two parts using ":", processes the second part and sends back the following message:

    ACARS_NEW|MODEL|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|N A

    or

    ACARS|MODEL|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA

    If the key word is different, the server stops the connection.

    In this case, the messages received by the server are:

    IGODISPATCHBOEING733:N/A|N/A|N/A|N/A|N/A|N/A|N/A|N/A|N/A
    I
    GODISPATCHBOEING733:N/A|N/A|N/A|N/A|N/A|N/A|N/A|N/A|N/A


    Connection interrupted. Again, this only happens when the server is running on Windows 10. It works just fine on Mac.

    I will greatly appreciate your help!

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: Java client sends a partial message to server although shows as a full message

    Since changing the server affects the message, and the server code is written in C++, I'm not sure why you think it's the Java side that has the issue?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: Java client sends a partial message to server although shows as a full message

    Thought of that too. But I have a similar client written in Swift (for an iOS application) and it works without a glitch with the same server in Windows, Mac, and Linux. The server still gets only first letter of the second message. So, there is something wrong in the combination Java Client and C++ Server in Windows that I can't figure out. Do you see any particular problems in the Java code?

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: Java client sends a partial message to server although shows as a full message

    Java Code:
                output = new DataOutputStream( socket.getOutputStream());
                output.writeBytes(messageToServer);
                output.flush();
    That's the relevant bit of code, and unless "messageToServer" has something odd in it (and there's nothing I can see, and it would be obvious in your logging) then the bytes will be sent.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,966
    Rep Power
    7

    Default Re: Java client sends a partial message to server although shows as a full message

    Quote Originally Posted by igorland View Post
    ACARS_NEW|MODEL|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|N A
    ACARS|MODEL|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA|NA
    BATMAN!!!


    Edit: All caps is not allowed so I need to add some extra text. What a joy this forum is :)
    Last edited by SurfMan; 03-13-2018 at 02:10 PM.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

Similar Threads

  1. Replies: 1
    Last Post: 07-21-2012, 10:49 AM
  2. Replies: 0
    Last Post: 07-15-2012, 07:57 AM
  3. message passing in Client/Server Chat problem
    By pappyj77 in forum Threads and Synchronization
    Replies: 19
    Last Post: 09-13-2011, 02:54 PM
  4. Partial message problem using nio socket
    By perl010101 in forum New To Java
    Replies: 0
    Last Post: 05-25-2011, 09:26 PM
  5. Java Message Server/Client help
    By sari in forum Networking
    Replies: 3
    Last Post: 03-20-2010, 11:17 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •