diff --git a/engine/src/networking/com/jme3/network/base/ConnectorAdapter.java b/engine/src/networking/com/jme3/network/base/ConnectorAdapter.java index 82734349f..968c6c8e9 100644 --- a/engine/src/networking/com/jme3/network/base/ConnectorAdapter.java +++ b/engine/src/networking/com/jme3/network/base/ConnectorAdapter.java @@ -35,6 +35,8 @@ package com.jme3.network.base; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; import com.jme3.network.Message; import com.jme3.network.MessageListener; @@ -63,7 +65,10 @@ public class ConnectorAdapter extends Thread private Connector connector; private MessageListener dispatcher; private AtomicBoolean go = new AtomicBoolean(true); - + + // Writes messages out on a background thread + private ExecutorService writer = Executors.newFixedThreadPool(1); + // Marks the messages as reliable or not if they came // through this connector. private boolean reliable; @@ -80,6 +85,9 @@ public class ConnectorAdapter extends Thread public void close() { go.set(false); + + // Kill the writer service + writer.shutdown(); // Kill the connector connector.close(); @@ -90,6 +98,11 @@ public class ConnectorAdapter extends Thread dispatcher.messageReceived( null, m ); } + public void write( ByteBuffer data ) + { + writer.execute( new MessageWriter(data) ); + } + public void run() { MessageProtocol protocol = new MessageProtocol(); @@ -116,4 +129,22 @@ public class ConnectorAdapter extends Thread } } + protected class MessageWriter implements Runnable + { + private ByteBuffer data; + + public MessageWriter( ByteBuffer data ) + { + this.data = data; + } + + public void run() + { + if( !go.get() ) + return; + connector.write(data); + } + } + + } diff --git a/engine/src/networking/com/jme3/network/base/DefaultClient.java b/engine/src/networking/com/jme3/network/base/DefaultClient.java index 19130db51..4c515f77f 100644 --- a/engine/src/networking/com/jme3/network/base/DefaultClient.java +++ b/engine/src/networking/com/jme3/network/base/DefaultClient.java @@ -204,13 +204,16 @@ public class DefaultClient implements Client // be called from multiple threads. If writing // is queued into its own thread then that could // be shared. + // Writing is now done on a background thread. + // If we ever share a ByteBuffer then it will need to be + // copied before handing off. ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); if( message.isReliable() || fast == null ) { if( reliable == null ) throw new RuntimeException( "No reliable connector configured" ); - reliable.write(buffer); + reliableAdapter.write(buffer); } else { - fast.write(buffer); + fastAdapter.write(buffer); } }