com.jme3.network.Message Java Examples

The following examples show how to use com.jme3.network.Message. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestChatClient.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void messageReceived(Client source, Message m) {
    ChatMessage chat = (ChatMessage) m;

    System.out.println("Received:" + chat);

    // One of the least efficient ways to add text to a
    // JEditorPane
    chatMessages.append("<font color='#00a000'>" + (m.isReliable() ? "TCP" : "UDP") + "</font>");
    chatMessages.append(" -- <font color='#000080'><b>" + chat.getName() + "</b></font> : ");
    chatMessages.append(chat.getMessage());
    chatMessages.append("<br />");
    String s = "<html><body>" + chatMessages + "</body></html>";
    chatLog.setText(s);

    // Set selection to the end so that the scroll panel will scroll
    // down.
    chatLog.select(s.length(), s.length());
}
 
Example #2
Source File: TestSerialization.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void messageReceived(HostedConnection source, Message m) {
    TestSerializationMessage cm = (TestSerializationMessage) m;
    System.out.println(cm.z);
    System.out.println(cm.b);
    System.out.println(cm.c);
    System.out.println(cm.s);
    System.out.println(cm.i);
    System.out.println(cm.f);
    System.out.println(cm.l);
    System.out.println(cm.d);
    System.out.println(Arrays.toString(cm.ia));
    System.out.println(cm.ls);
    System.out.println(cm.mp);
    System.out.println(cm.status1);
    System.out.println(cm.status2);
    System.out.println(cm.date);
}
 
Example #3
Source File: TestChatServer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void messageReceived(HostedConnection source, Message m) {
    if (m instanceof ChatMessage) {
        // Keep track of the name just in case we 
        // want to know it for some other reason later and it's
        // a good example of session data
        source.setAttribute("name", ((ChatMessage) m).getName());

        System.out.println("Broadcasting:" + m + "  reliable:" + m.isReliable());

        // Just rebroadcast... the reliable flag will stay the
        // same so if it came in on UDP it will go out on that too
        source.getServer().broadcast(m);
    } else {
        System.err.println("Received odd message:" + m);
    }
}
 
Example #4
Source File: TestChatClient.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void messageReceived(Client source, Message m) {
    ChatMessage chat = (ChatMessage) m;

    System.out.println("Received:" + chat);

    // One of the least efficient ways to add text to a
    // JEditorPane
    chatMessages.append("<font color='#00a000'>" + (m.isReliable() ? "TCP" : "UDP") + "</font>");
    chatMessages.append(" -- <font color='#000080'><b>" + chat.getName() + "</b></font> : ");
    chatMessages.append(chat.getMessage());
    chatMessages.append("<br />");
    String s = "<html><body>" + chatMessages + "</body></html>";
    chatLog.setText(s);

    // Set selection to the end so that the scroll panel will scroll
    // down.
    chatLog.select(s.length(), s.length());
}
 
Example #5
Source File: GZIPSerializer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void writeObject(ByteBuffer buffer, Object object) throws IOException {
    if (!(object instanceof GZIPCompressedMessage)) return;
    Message message = ((GZIPCompressedMessage)object).getMessage();

    ByteBuffer tempBuffer = ByteBuffer.allocate(512000);
    Serializer.writeClassAndObject(tempBuffer, message);

    ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
    GZIPOutputStream gzipOutput = new GZIPOutputStream(byteArrayOutput);

    gzipOutput.write(tempBuffer.array());
    gzipOutput.flush();
    gzipOutput.finish();
    gzipOutput.close();

    buffer.put(byteArrayOutput.toByteArray());
}
 
Example #6
Source File: ZIPSerializer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void writeObject(ByteBuffer buffer, Object object) throws IOException {
    if (!(object instanceof ZIPCompressedMessage)) return;

    ZIPCompressedMessage zipMessage = (ZIPCompressedMessage)object;
    Message message = zipMessage.getMessage();
    ByteBuffer tempBuffer = ByteBuffer.allocate(512000);
    Serializer.writeClassAndObject(tempBuffer, message);

    ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
    ZipOutputStream zipOutput = new ZipOutputStream(byteArrayOutput);
    zipOutput.setLevel(zipMessage.getLevel());

    ZipEntry zipEntry = new ZipEntry("zip");

    zipOutput.putNextEntry(zipEntry);
    zipOutput.write(tempBuffer.array());
    zipOutput.flush();
    zipOutput.closeEntry();
    zipOutput.close();

    buffer.put(byteArrayOutput.toByteArray());
}
 
Example #7
Source File: MessageProtocol.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 *  Converts a message to a ByteBuffer using the Serializer
 *  and the (short length) + data protocol.  If target is null
 *  then a 32k byte buffer will be created and filled.
 */
public static ByteBuffer messageToBuffer( Message message, ByteBuffer target )
{
    // Could let the caller pass their own in       
    ByteBuffer buffer = target == null ? ByteBuffer.allocate( 32767 + 2 ) : target;
    
    try {
        buffer.position( 2 );
        Serializer.writeClassAndObject( buffer, message );
        buffer.flip();
        short dataLength = (short)(buffer.remaining() - 2);
        buffer.putShort( dataLength );
        buffer.position( 0 );
        
        return buffer;
    } catch( IOException e ) {
        throw new RuntimeException( "Error serializing message", e );
    }
}
 
Example #8
Source File: SerializerMessageProtocol.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 *  Converts a message to a ByteBuffer using the com.jme3.network.serializing.Serializer
 *  and the (short length) + data protocol.  If target is null
 *  then a 32k byte buffer will be created and filled.
 */
@Override
public ByteBuffer toByteBuffer( Message message, ByteBuffer target ) {

    // Could let the caller pass their own in       
    ByteBuffer buffer = target == null ? ByteBuffer.allocate(32767 + 2) : target;
    
    try {
        buffer.position(2);
        Serializer.writeClassAndObject(buffer, message);
        buffer.flip();
        short dataLength = (short)(buffer.remaining() - 2);
        buffer.putShort(dataLength);
        buffer.position(0);
        
        return buffer;
    } catch( IOException e ) {
        throw new RuntimeException("Error serializing message", e);
    }
}
 
Example #9
Source File: GZIPSerializer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void writeObject(ByteBuffer buffer, Object object) throws IOException {
    if (!(object instanceof GZIPCompressedMessage)) return;
    Message message = ((GZIPCompressedMessage)object).getMessage();

    ByteBuffer tempBuffer = ByteBuffer.allocate(512000);
    Serializer.writeClassAndObject(tempBuffer, message);

    ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
    GZIPOutputStream gzipOutput = new GZIPOutputStream(byteArrayOutput);

    tempBuffer.flip();
    gzipOutput.write(tempBuffer.array(), 0, tempBuffer.limit());
    gzipOutput.flush();
    gzipOutput.finish();
    gzipOutput.close();

    buffer.put(byteArrayOutput.toByteArray());
}
 
Example #10
Source File: ZIPSerializer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void writeObject(ByteBuffer buffer, Object object) throws IOException {
    if (!(object instanceof ZIPCompressedMessage)) return;

    ZIPCompressedMessage zipMessage = (ZIPCompressedMessage)object;
    Message message = zipMessage.getMessage();
    ByteBuffer tempBuffer = ByteBuffer.allocate(512000);
    Serializer.writeClassAndObject(tempBuffer, message);

    ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
    ZipOutputStream zipOutput = new ZipOutputStream(byteArrayOutput);
    zipOutput.setLevel(zipMessage.getLevel());

    ZipEntry zipEntry = new ZipEntry("zip");

    zipOutput.putNextEntry(zipEntry);
    tempBuffer.flip();
    zipOutput.write(tempBuffer.array(), 0, tempBuffer.limit());
    zipOutput.flush();
    zipOutput.closeEntry();
    zipOutput.close();

    buffer.put(byteArrayOutput.toByteArray());
}
 
Example #11
Source File: KernelAdapter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 *  Note on threading for those writing their own server 
 *  or adapter implementations.  The rule that a single connection be 
 *  processed by only one thread at a time is more about ensuring that
 *  the messages are delivered in the order that they are received
 *  than for any user-code safety.  99% of the time the user code should
 *  be writing for multithreaded access anyway.
 *
 *  <p>The issue with the messages is that if an implementation is
 *  using a general thread pool then it would be possible for a 
 *  naive implementation to have one thread grab an Envelope from
 *  connection 1's and another grab the next Envelope.  Since an Envelope
 *  may contain several messages, delivering the second thread's messages
 *  before or during the first's would be really confusing and hard
 *  to code for in user code.</p>
 *
 *  <p>And that's why this note is here.  DefaultServer does a rudimentary
 *  per-connection locking but it couldn't possibly guard against
 *  out of order Envelope processing.</p>    
 */
protected void dispatch( Endpoint p, Message m )
{
    // Because this class is the only one with the information
    // to do it... we need to pull of the registration message
    // here.
    if( m instanceof ClientRegistrationMessage ) {
        server.registerClient( this, p, (ClientRegistrationMessage)m );
        return;           
    }                
 
    try {           
        HostedConnection source = getConnection(p);
        if( source == null ) {
            if( reliable ) {
                // If it's a reliable connection then it's slightly more
                // concerning but this can happen all the time for a UDP endpoint.
                log.log( Level.WARNING, "Received message from unconnected endpoint:" + p + "  message:" + m );
            }                    
            return; 
        }
        messageDispatcher.messageReceived( source, m );
    } catch( Exception e ) {
        reportError(p, m, e);
    }
}
 
Example #12
Source File: MessageProtocol.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 *  Creates a message from the properly sized byte buffer
 *  and adds it to the messages queue.
 */   
protected void createMessage( ByteBuffer buffer )
{
    try {
        Object obj = Serializer.readClassAndObject( buffer );
        Message m = (Message)obj;
        messages.add(m);
    } catch( IOException e ) {
        throw new RuntimeException( "Error deserializing object", e );   
    }         
}
 
Example #13
Source File: SerializerMessageProtocol.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *  Creates and returns a message from the properly sized byte buffer
 *  using com.jme3.network.serializing.Serializer.
 */   
@Override
public Message toMessage( ByteBuffer bytes ) {
    try {
        return (Message)Serializer.readClassAndObject(bytes);
    } catch( IOException e ) {
        throw new RuntimeException("Error deserializing object, class ID:" + bytes.getShort(0), e);   
    }         
}
 
Example #14
Source File: GreedyMessageBuffer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *  Returns the next message in the buffer or null if there are no more
 *  messages in the buffer.  
 */
@Override
public Message pollMessage() {
    if( messages.isEmpty() ) {
        return null;
    }                
    return messages.removeFirst();
}
 
Example #15
Source File: TestThroughput.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
    public void messageReceived(MessageConnection source, Message msg) {

        if (!isOnServer) {
            // It's local to the client so we got it back
            counter++;
            total++;
            long time = System.currentTimeMillis();
//System.out.println( "total:" + total + "  counter:" + counter + "  lastTime:" + lastTime + "  time:" + time );
            if (lastTime < 0) {
                lastTime = time;
            } else if (time - lastTime > 1000) {
                long delta = time - lastTime;
                double scale = delta / 1000.0;
                double pps = counter / scale;
                System.out.println("messages per second:" + pps + "  total messages:" + total);
                counter = 0;
                lastTime = time;
            }
        } else {
            if (source == null) {
                System.out.println("Received a message from a not fully connected source, msg:" + msg);
            } else {
//System.out.println( "sending:" + msg + " back to client:" + source );
                // The 'reliable' flag is transient and the server doesn't
                // (yet) reset this value for us.
                ((com.jme3.network.Message) msg).setReliable(testReliable);
                source.send(msg);
            }
        }
    }
 
Example #16
Source File: LazyMessageBuffer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *  Returns the next message in the buffer or null if there are no more
 *  messages in the buffer.  
 */
@Override
public Message pollMessage() {
    if( messages.isEmpty() ) {
        return null;
    }
    ByteBuffer bytes = messages.removeFirst();
    return protocol.toMessage(bytes);                
}
 
Example #17
Source File: GZIPSerializer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {
    try
    {
        GZIPCompressedMessage result = new GZIPCompressedMessage();

        byte[] byteArray = new byte[data.remaining()];

        data.get(byteArray);

        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(byteArray));
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] tmp = new byte[9012];
        int read;

        while (in.available() > 0 && ((read = in.read(tmp)) > 0)) {
            out.write(tmp, 0, read);
        }

        result.setMessage((Message)Serializer.readClassAndObject(ByteBuffer.wrap(out.toByteArray())));
        return (T)result;
    }
    catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.toString());
    }
}
 
Example #18
Source File: KernelAdapter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void createAndDispatch( Envelope env )
{
    MessageBuffer protocol = getMessageBuffer(env.getSource()); 

    byte[] data = env.getData();
    ByteBuffer buffer = ByteBuffer.wrap(data);

    if( !protocol.addBytes(buffer) ) {
        // This can happen if there was only a partial message
        // received.  However, this should never happen for unreliable
        // connections.
        if( !reliable ) {
            // Log some additional information about the packet.
            int len = Math.min( 10, data.length );
            StringBuilder sb = new StringBuilder();
            for( int i = 0; i < len; i++ ) {
                sb.append( "[" + Integer.toHexString(data[i]) + "]" ); 
            }
            log.log( Level.FINE, "First 10 bytes of incomplete nessage:" + sb );         
            throw new RuntimeException( "Envelope contained incomplete data:" + env );
        }                
    }            
    
    // Should be complete... and maybe we should check but we don't
    Message m = null;
    while( (m = protocol.pollMessage()) != null ) {
        m.setReliable(reliable);
        dispatch(env.getSource(), m);
    }
}
 
Example #19
Source File: ZIPSerializer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {
    try
    {
        ZIPCompressedMessage result = new ZIPCompressedMessage();

        byte[] byteArray = new byte[data.remaining()];

        data.get(byteArray);

        ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(byteArray));
        in.getNextEntry();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] tmp = new byte[9012];
        int read;

        while (in.available() > 0 && ((read = in.read(tmp)) > 0)) {
            out.write(tmp, 0, read);
        }

        in.closeEntry();
        out.flush();
        in.close();

        result.setMessage((Message)Serializer.readClassAndObject(ByteBuffer.wrap(out.toByteArray())));
        return (T)result;
    }
    catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.toString());
    }
}
 
Example #20
Source File: ConnectorAdapter.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void run()
{
    MessageProtocol protocol = new MessageProtocol();
 
    try {                  
        while( go.get() ) {
            ByteBuffer buffer = connector.read();
            if( buffer == null ) {
                if( go.get() ) {
                    throw new ConnectorException( "Connector closed." ); 
                } else {
                    // Just dump out because a null buffer is expected
                    // from a closed/closing connector
                    break;
                }
            }
            
            protocol.addBuffer( buffer );
            
            Message m = null;
            while( (m = protocol.getMessage()) != null ) {
                m.setReliable( reliable );
                dispatch( m );
            }
        }
    } catch( Exception e ) {
        handleError( e );
    }            
}
 
Example #21
Source File: ConnectorAdapter.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void run()
{
    MessageBuffer messageBuffer = protocol.createBuffer();
 
    try {                  
        while( go.get() ) {
            ByteBuffer buffer = connector.read();
            if( buffer == null ) {
                if( go.get() ) {
                    throw new ConnectorException( "Connector closed." ); 
                } else {
                    // Just dump out because a null buffer is expected
                    // from a closed/closing connector
                    break;
                }
            }
            
            messageBuffer.addBytes(buffer);
            
            Message m = null;
            while( (m = messageBuffer.pollMessage()) != null ) {
                m.setReliable( reliable );
                dispatch( m );
            }
        }
    } catch( Exception e ) {
        handleError( e );
    }            
}
 
Example #22
Source File: MessageProtocol.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 *  Retrieves and removes an extracted message from the accumulated buffer
 *  or returns null if there are no more messages.
 */
public Message getMessage()
{
    if( messages.isEmpty() ) {
        return null;
    }
    
    return messages.removeFirst();
}
 
Example #23
Source File: MessageListener.java    From OpenRTS with MIT License 5 votes vote down vote up
@Override
public void messageReceived(HostedConnection source, Message message) {
	if (message instanceof InputEvent) {
		// do something with the message
		InputEvent helloMessage = (InputEvent) message;
		logger.info("Client #" + source.getId() + " received: '" + helloMessage.getActionCommand() + "'");
		source.getServer().broadcast(Filters.notEqualTo(source), message);
	}
}
 
Example #24
Source File: MessageListener.java    From OpenRTS with MIT License 5 votes vote down vote up
@Override
public void messageReceived(Client source, Message message) {
	if (message instanceof InputEvent) {
		// do something with the message
		InputEvent helloMessage = (InputEvent) message;
		System.out.println("Client #" + source.getId() + " received: '" + helloMessage.getActionCommand() + "'");
		EventManager.post(helloMessage);
	} // else...
}
 
Example #25
Source File: AbstractMessageDelegator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *  Returns true if the specified method is valid for the specified
 *  message type.  This is used internally during automapping to
 *  provide implementation specific filtering of methods.
 *  This implementation checks for methods that take either the connection and message 
 *  type arguments (in that order) or just the message type.
 */
protected boolean isValidMethod( Method m, Class messageType ) {
 
    if( log.isLoggable(Level.FINEST) ) {
        log.log(Level.FINEST, "isValidMethod({0}, {1})", new Object[]{m, messageType});
    }
           
    // Parameters must be S and message type or just message type
    Class<?>[] parms = m.getParameterTypes();
    if( parms.length != 2 && parms.length != 1 ) {
        log.finest("Parameter count is not 1 or 2");
        return false;
    }                   
    int messageIndex = 0;
    if( parms.length > 1 ) {
        if( MessageConnection.class.isAssignableFrom(parms[0]) ) {
            messageIndex++;
        } else {
            log.finest("First parameter is not a MessageConnection or subclass.");
            return false;
        }
    }
 
    if( messageType == null && !Message.class.isAssignableFrom(parms[messageIndex]) ) {
        log.finest("Second parameter is not a Message or subclass.");
        return false;
    }
    if( messageType != null && !parms[messageIndex].isAssignableFrom(messageType) ) {
        log.log(Level.FINEST, "Second parameter is not a {0}", messageType);
        return false;
    }
    return true;            
}
 
Example #26
Source File: GZIPSerializer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {
    try
    {
        GZIPCompressedMessage result = new GZIPCompressedMessage();

        byte[] byteArray = new byte[data.remaining()];

        data.get(byteArray);

        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(byteArray));
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] tmp = new byte[9012];
        int read;

        while (in.available() > 0 && ((read = in.read(tmp)) > 0)) {
            out.write(tmp, 0, read);
        }

        result.setMessage((Message)Serializer.readClassAndObject(ByteBuffer.wrap(out.toByteArray())));
        return (T)result;
    }
    catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.toString());
    }
}
 
Example #27
Source File: ZIPSerializer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {
    try
    {
        ZIPCompressedMessage result = new ZIPCompressedMessage();

        byte[] byteArray = new byte[data.remaining()];

        data.get(byteArray);

        ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(byteArray));
        in.getNextEntry();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] tmp = new byte[9012];
        int read;

        while (in.available() > 0 && ((read = in.read(tmp)) > 0)) {
            out.write(tmp, 0, read);
        }

        in.closeEntry();
        out.flush();
        in.close();

        result.setMessage((Message)Serializer.readClassAndObject(ByteBuffer.wrap(out.toByteArray())));
        return (T)result;
    }
    catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.toString());
    }
}
 
Example #28
Source File: CompressedMessage.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public CompressedMessage(Message msg) {
    this.message = msg;
}
 
Example #29
Source File: CompressedMessage.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setMessage(Message message) {
    this.message = message;
}
 
Example #30
Source File: CompressedMessage.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Message getMessage() {
    return message;
}