Skip to content
Davidiusdadi edited this page Apr 25, 2012 · 3 revisions

This aricle is incomplete.

Introduction

Using Java-Websocket is very similar to using javascript websocktes: You simply take the client or the server class and override its abstract methods by putting your appilication logic in place.

These methods are

  • onOpen
  • onMessage
  • onClose
  • onError

The Server

Example

import java.net.InetSocketAddress;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketServer;
import org.java_websocket.handshake.ClientHandshake;

public class SimpleServer extends WebSocketServer {

	public SimpleServer( InetSocketAddress address ) {
		super( address );
	}

	@Override
	public void onOpen( WebSocket conn, ClientHandshake handshake ) {
		System.out.println( "new connection to " + conn.getRemoteSocketAddress() );
	}

	@Override
	public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
		System.out.println( "closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason );
	}

	@Override
	public void onMessage( WebSocket conn, String message ) {
		System.out.println( "received message form " + conn.getRemoteSocketAddress() + ": " + message );
	}

	@Override
	public void onError( WebSocket conn, Exception ex ) {
		System.out.println( "an error occured on connection " + conn + ":" + ex );
	}

}

TheClient

Example

import java.net.URI;
import java.net.URISyntaxException;

import org.java_websocket.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.handshake.ServerHandshake;

public class EmptyClient extends WebSocketClient {

	public EmptyClient( URI serverUri , Draft draft ) {
		super( serverUri, draft );
	}

	public EmptyClient( URI serverURI ) {
		super( serverURI );
	}

	@Override
	public void onOpen( ServerHandshake handshakedata ) {
	}

	@Override
	public void onMessage( String message ) {
	}

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

	@Override
	public void onError( Exception ex ) {
	}

	public static void main( String[] args ) throws URISyntaxException {
		EmptyClient c = new EmptyClient( new URI( "ws://localhost:8887" ), new Draft_10() );
		c.connect();
	}

}

Clone this wiki locally