2525import java .nio .channels .SelectionKey ;
2626import java .util .ArrayList ;
2727import java .util .Collection ;
28+ import java .util .Collections ;
2829import java .util .List ;
2930import java .util .concurrent .BlockingQueue ;
3031import java .util .concurrent .LinkedBlockingQueue ;
@@ -110,6 +111,11 @@ public class WebSocketImpl implements WebSocket {
110111 */
111112 private long lastPong = System .currentTimeMillis ();
112113
114+ /**
115+ * Attribut to synchronize the write
116+ */
117+ private static final Object synchronizeWriteObject = new Object ();
118+
113119 /**
114120 * Creates a websocket with server role
115121 *
@@ -209,8 +215,8 @@ private boolean decodeHandshake( ByteBuffer socketBufferNew ) {
209215 HandshakeState isflashedgecase = isFlashEdgeCase ( socketBuffer );
210216 if ( isflashedgecase == HandshakeState .MATCHED ) {
211217 try {
212- write ( ByteBuffer .wrap ( Charsetfunctions .utf8Bytes ( wsl .getFlashPolicy ( this ) ) ) );
213- close ( CloseFrame .FLASHPOLICY , "" );
218+ write ( Collections . singletonList ( ByteBuffer .wrap (Charsetfunctions .utf8Bytes (wsl .getFlashPolicy (this )))) );
219+ close (CloseFrame .FLASHPOLICY , "" );
214220 } catch ( InvalidDataException e ) {
215221 close ( CloseFrame .ABNORMAL_CLOSE , "remote peer closed connection before flashpolicy could be transmitted" , true );
216222 }
@@ -623,9 +629,13 @@ public void send( byte[] bytes ) throws IllegalArgumentException, WebsocketNotCo
623629 private void send ( Collection <Framedata > frames ) {
624630 if ( !isOpen () )
625631 throw new WebsocketNotConnectedException ();
626- for ( Framedata f : frames ) {
627- sendFrame ( f );
632+ ArrayList <ByteBuffer > outgoingFrames = new ArrayList <ByteBuffer >();
633+ for (Framedata f : frames ) {
634+ if ( DEBUG )
635+ System .out .println ( "send frame: " + f );
636+ outgoingFrames .add ( draft .createBinaryFrame ( f ) );
628637 }
638+ write ( outgoingFrames );
629639 }
630640
631641 @ Override
@@ -635,9 +645,7 @@ public void sendFragmentedFrame( Opcode op, ByteBuffer buffer, boolean fin ) {
635645
636646 @ Override
637647 public void sendFrame ( Framedata framedata ) {
638- if ( DEBUG )
639- System .out .println ( "send frame: " + framedata );
640- write ( draft .createBinaryFrame ( framedata ) );
648+ send ( Collections .singletonList ( framedata ) );
641649 }
642650
643651 public void sendPing () throws NotYetConnectedException {
@@ -707,8 +715,10 @@ private void write( ByteBuffer buf ) {
707715 }
708716
709717 private void write ( List <ByteBuffer > bufs ) {
710- for ( ByteBuffer b : bufs ) {
711- write ( b );
718+ synchronized ( synchronizeWriteObject ) {
719+ for (ByteBuffer b : bufs ) {
720+ write (b );
721+ }
712722 }
713723 }
714724
0 commit comments