Skip to content

Commit

Permalink
made websocket callback functions provide more informations.
Browse files Browse the repository at this point in the history
InvalidDataException will now be thrown in cases a  CharacterCodingException had been thrown before
  • Loading branch information
Davidiusdadi committed Feb 4, 2012
1 parent 1201512 commit d23d08f
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 77 deletions.
5 changes: 3 additions & 2 deletions example/AutobahnClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.net.URI;

import net.tootallnate.websocket.Draft;
import net.tootallnate.websocket.Handshakedata;
import net.tootallnate.websocket.WebSocket;
import net.tootallnate.websocket.WebSocketClient;
import net.tootallnate.websocket.drafts.Draft_17;
Expand Down Expand Up @@ -149,11 +150,11 @@ public void onError( Exception ex ) {
}

@Override
public void onOpen() {
public void onOpen( Handshakedata handshake ) {
}

@Override
public void onClose( int code, String reason ) {
public void onClose( int code, String reason, boolean remote ) {
System.out.println( "Closed: " + code + " " + reason );
}

Expand Down
14 changes: 7 additions & 7 deletions example/AutobahnServerTest.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import net.tootallnate.websocket.Draft;
import net.tootallnate.websocket.Handshakedata;
import net.tootallnate.websocket.WebSocket;
import net.tootallnate.websocket.WebSocketServer;
import net.tootallnate.websocket.drafts.Draft_17;
Expand All @@ -11,21 +11,21 @@ public class AutobahnServerTest extends WebSocketServer {
private static int counter = 0;

public AutobahnServerTest( int port, Draft d ) throws UnknownHostException {
super( new InetSocketAddress( InetAddress.getLocalHost(), port ),d );
super( new InetSocketAddress( "localhost", port ), d );
}

public AutobahnServerTest( InetSocketAddress address, Draft d ) {
super( address, d );
}

@Override
public void onClientOpen( WebSocket conn ) {
public void onClientOpen( WebSocket conn, Handshakedata handshake ) {
counter++;
System.out.println( "Opened connection number" + counter );
System.out.println( "///////////Opened connection number" + counter );
}

@Override
public void onClientClose( WebSocket conn ) {
public void onClientClose( WebSocket conn, int code, String reason, boolean remote ) {
}

@Override
Expand Down Expand Up @@ -56,12 +56,12 @@ public void onMessage( WebSocket conn, byte[] blob ) {
}

public static void main( String[] args ) throws UnknownHostException {
WebSocket.DEBUG = true;
WebSocket.DEBUG = false;
int port;
try {
port = new Integer( args[ 0 ] );
} catch ( Exception e ) {
System.out.println( "No port specified. Defaulting to 9001" );
System.out.println( "No port specified. Defaulting to 9003" );
port = 9003;
}
new AutobahnServerTest( port, new Draft_17() ).start();
Expand Down
5 changes: 3 additions & 2 deletions example/ChatClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import javax.swing.JTextField;

import net.tootallnate.websocket.Draft;
import net.tootallnate.websocket.Handshakedata;
import net.tootallnate.websocket.WebSocket;
import net.tootallnate.websocket.WebSocketClient;
import net.tootallnate.websocket.drafts.Draft_10;
Expand Down Expand Up @@ -108,12 +109,12 @@ public void onMessage( String message ) {
ta.setCaretPosition( ta.getDocument().getLength() );
}

public void onOpen() {
public void onOpen( Handshakedata handshake ) {
ta.append( "You are connected to ChatServer: " + getURI() + "\n" );
ta.setCaretPosition( ta.getDocument().getLength() );
}

public void onClose( int code, String reason ) {
public void onClose( int code, String reason, boolean remote ) {
ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" );
ta.setCaretPosition( ta.getDocument().getLength() );
connect.setEnabled( true );
Expand Down
5 changes: 3 additions & 2 deletions example/ChatServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import net.tootallnate.websocket.Handshakedata;
import net.tootallnate.websocket.WebSocket;
import net.tootallnate.websocket.WebSocketServer;

Expand All @@ -21,7 +22,7 @@ public ChatServer( InetSocketAddress address ) {
super( address );
}

public void onClientOpen( WebSocket conn ) {
public void onClientOpen( WebSocket conn, Handshakedata handshake ) {
try {
this.sendToAll( conn + " entered the room!" );
} catch ( InterruptedException ex ) {
Expand All @@ -30,7 +31,7 @@ public void onClientOpen( WebSocket conn ) {
System.out.println( conn + " entered the room!" );
}

public void onClientClose( WebSocket conn ) {
public void onClientClose( WebSocket conn, int code, String reason, boolean remote ) {
try {
this.sendToAll( conn + " has left the room!" );
} catch ( InterruptedException ex ) {
Expand Down
13 changes: 10 additions & 3 deletions src/net/tootallnate/websocket/Charsetfunctions.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;

import net.tootallnate.websocket.exeptions.InvalidDataException;

public class Charsetfunctions {

public static CodingErrorAction codingErrorAction = CodingErrorAction.REPORT;
Expand Down Expand Up @@ -45,16 +47,21 @@ public static String stringAscii( byte[] bytes, int offset, int length ){
}
}

public static String stringUtf8( byte[] bytes ) throws CharacterCodingException {
public static String stringUtf8( byte[] bytes ) throws InvalidDataException {
return stringUtf8( bytes, 0, bytes.length );
}

public static String stringUtf8( byte[] bytes, int off, int length ) throws CharacterCodingException {
public static String stringUtf8( byte[] bytes, int off, int length ) throws InvalidDataException {
CharsetDecoder decode = Charset.forName( "UTF8" ).newDecoder();
decode.onMalformedInput( codingErrorAction );
decode.onUnmappableCharacter( codingErrorAction );
//decode.replaceWith( "X" );
String s = decode.decode( ByteBuffer.wrap( bytes, off, length ) ).toString();
String s;
try {
s = decode.decode( ByteBuffer.wrap( bytes, off, length ) ).toString();
} catch ( CharacterCodingException e ) {
throw new InvalidDataException( CloseFrame.NO_UTF8, e );
}
return s;
}
}
5 changes: 2 additions & 3 deletions src/net/tootallnate/websocket/CloseFrame.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package net.tootallnate.websocket;

import java.nio.charset.CharacterCodingException;

import net.tootallnate.websocket.exeptions.InvalidDataException;
import net.tootallnate.websocket.exeptions.InvalidFrameException;

public interface CloseFrame extends Framedata {
Expand Down Expand Up @@ -80,5 +79,5 @@ public interface CloseFrame extends Framedata {
public static final int BUGGYCLOSE = -2;

public int getCloseCode() throws InvalidFrameException;
public String getMessage() throws CharacterCodingException , InvalidFrameException;
public String getMessage() throws InvalidDataException;
}
9 changes: 2 additions & 7 deletions src/net/tootallnate/websocket/CloseFrameBuilder.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package net.tootallnate.websocket;

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;

import net.tootallnate.websocket.exeptions.InvalidDataException;
import net.tootallnate.websocket.exeptions.InvalidFrameException;
Expand Down Expand Up @@ -61,7 +60,7 @@ public int getCloseCode() {
return code;
}

private void initMessage() throws CharacterCodingException , InvalidFrameException {
private void initMessage() throws InvalidDataException {
if( code == CloseFrame.NOCODE ) {
reason = Charsetfunctions.stringUtf8( getPayloadData() );
} else {
Expand All @@ -84,11 +83,7 @@ public String toString() {
public void setPayload( byte[] payload ) throws InvalidDataException {
super.setPayload( payload );
initCloseCode();
try {
initMessage();
} catch ( CharacterCodingException e ) {
throw new InvalidDataException( CloseFrame.NO_UTF8 );
}
initMessage();
}
@Override
public byte[] getPayloadData() {
Expand Down
21 changes: 11 additions & 10 deletions src/net/tootallnate/websocket/WebSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
Expand Down Expand Up @@ -171,7 +170,7 @@ private void init( WebSocketListener listener, Draft draft, SocketChannel sockch
HandshakeBuilder response = wsl.onHandshakeRecievedAsServer( this, d, handshake );
writeDirect( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ), role ) );
draft = d;
open();
open( handshake );
handleRead();
return;
} else if( handshakestate == HandshakeState.MATCHING ) {
Expand Down Expand Up @@ -202,7 +201,7 @@ private void init( WebSocketListener listener, Draft draft, SocketChannel sockch
handshakestate = draft.acceptHandshakeAsServer( handshake );

if( handshakestate == HandshakeState.MATCHED ) {
open();
open( handshake );
handleRead();
} else if( handshakestate != HandshakeState.MATCHING ) {
close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" );
Expand All @@ -214,7 +213,7 @@ private void init( WebSocketListener listener, Draft draft, SocketChannel sockch
handshake = draft.translateHandshake( socketBuffer );
handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake );
if( handshakestate == HandshakeState.MATCHED ) {
open();
open( handshake );
handleRead();
} else if( handshakestate == HandshakeState.MATCHING ) {
return;
Expand Down Expand Up @@ -313,6 +312,8 @@ public void closeDirect( int code, String message ) throws IOException {
wsl.onError( this, e );
closeConnection( CloseFrame.ABNROMAL_CLOSE, "generated frame is invalid", false );
}
} else {
closeConnection( CloseFrame.NEVERCONNECTED, false );
}
if( code == CloseFrame.PROTOCOL_ERROR )// this endpoint found a PROTOCOL_ERROR
closeConnection( code, false );
Expand Down Expand Up @@ -342,7 +343,7 @@ public void closeConnection( int code, String message, boolean remote ) {
} catch ( IOException e ) {
wsl.onError( this, e );
}
this.wsl.onClose( this, code, message );
this.wsl.onClose( this, code, message, remote );
if( draft != null )
draft.reset();
currentframe = null;
Expand Down Expand Up @@ -380,11 +381,11 @@ public void send( byte[] bytes ) throws IllegalArgumentException , NotYetConnect
send( draft.createFrames( bytes, role == Role.CLIENT ) );
}

private void send( Collection<Framedata> frames ) throws InterruptedException { // TODO instead of throwing or returning an error this method maybe should block on queue jams
private void send( Collection<Framedata> frames ) throws InterruptedException {
if( !this.handshakeComplete )
throw new NotYetConnectedException();
for( Framedata f : frames ) {
sendFrame( f ); // TODO high frequently calls to sendFrame are inefficient.
sendFrame( f );
}
}

Expand Down Expand Up @@ -464,7 +465,7 @@ private void writeDirect( List<ByteBuffer> bufs ) throws IOException {
channelWriteDirect( b );
}
}
private void deliverMessage( Framedata d ) throws CharacterCodingException {
private void deliverMessage( Framedata d ) throws InvalidDataException {
if( d.getOpcode() == Opcode.TEXT ) {
wsl.onMessage( this, Charsetfunctions.stringUtf8( d.getPayloadData() ) );
} else if( d.getOpcode() == Opcode.BINARY ) {
Expand All @@ -476,11 +477,11 @@ private void deliverMessage( Framedata d ) throws CharacterCodingException {
}
}

private void open() throws IOException {
private void open( Handshakedata d ) throws IOException {
if( DEBUG )
System.out.println( "open using draft: " + draft.getClass().getSimpleName() );
handshakeComplete = true;
wsl.onOpen( this );
wsl.onOpen( this, d );
}

public InetSocketAddress getRemoteSocketAddress() {
Expand Down
4 changes: 2 additions & 2 deletions src/net/tootallnate/websocket/WebSocketAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ public void onMessage( WebSocket conn, String message ) {
}

@Override
public void onOpen( WebSocket conn ) {
public void onOpen( WebSocket conn, Handshakedata handshake ) {
}

@Override
public void onClose( WebSocket conn, int code, String reason ) {
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
}

@Override
Expand Down
55 changes: 25 additions & 30 deletions src/net/tootallnate/websocket/WebSocketClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.nio.charset.CharacterCodingException;
import java.util.Iterator;
import java.util.Set;

Expand Down Expand Up @@ -156,31 +155,27 @@ protected void interruptableRun() {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
try {
key = i.next();
i.remove();
if( key.isReadable() ) {
conn.handleRead();
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
key = i.next();
i.remove();
if( key.isReadable() ) {
conn.handleRead();
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
} catch ( CharacterCodingException e ) {
conn.close( CloseFrame.NO_UTF8 );
}
}
}
Expand Down Expand Up @@ -261,8 +256,8 @@ public void onMessage( WebSocket conn, String message ) {
* @param conn
*/
@Override
public void onOpen( WebSocket conn ) {
onOpen();
public void onOpen( WebSocket conn, Handshakedata handshake ) {
onOpen( handshake );
}

/**
Expand All @@ -271,9 +266,9 @@ public void onOpen( WebSocket conn ) {
* @param conn
*/
@Override
public void onClose( WebSocket conn, int code, String reason ) {
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
thread.interrupt();
onClose( code, reason );
onClose( code, reason, remote );
}

/**
Expand All @@ -293,7 +288,7 @@ public void onWriteDemand( WebSocket conn ) {

// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onMessage( String message );
public abstract void onOpen();
public abstract void onClose( int code, String reason );
public abstract void onOpen( Handshakedata handshakedata );
public abstract void onClose( int code, String reason, boolean remote );
public abstract void onError( Exception ex );
}
Loading

0 comments on commit d23d08f

Please sign in to comment.