package kr.co.swh.lecture.opensource.websocket; 

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Collections;

import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

/**
 * <pre>
 * kr.co.swh.lecture.opensource.websocket 
 * ExampleServer.java
 *
 * 설명 :
 * </pre>
 * 
 * @since : 2020. 8. 2.
 * @author : tobby48
 * @version : v1.0
 */
public class ExampleServer extends WebSocketServer {

	public static void main(String[] args) throws UnknownHostException {
		ExampleServer server = new ExampleServer(8887);
		server.setReuseAddr(true);
		server.setTcpNoDelay(false);
		server.start();
	}
	public ExampleServer( int port ) throws UnknownHostException {
		super( new InetSocketAddress( port ) );
	}

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

	public ExampleServer(int port, Draft_6455 draft) {
		super( new InetSocketAddress( port ), Collections.<Draft>singletonList(draft));
	}

	@Override
	public void onOpen( WebSocket conn, ClientHandshake handshake ) {
		conn.send("Welcome to the server!"); //This method sends a message to the new client
		broadcast( "new connection: " + handshake.getResourceDescriptor() ); //This method sends a message to all clients connected
		System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!" );
	}

	@Override
	public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
		broadcast( conn + " has left the room!" );
		System.out.println( conn + " has left the room!" );
	}

	@Override
	public void onMessage( WebSocket conn, String message ) {
		broadcast( message );
		System.out.println( conn + ": " + message );
	}
	@Override
	public void onMessage( WebSocket conn, ByteBuffer message ) {
		broadcast( message.array() );
		System.out.println( conn + ": " + message );
	}
	
	@Override
	public void onError( WebSocket conn, Exception ex ) {
		ex.printStackTrace();
		if( conn != null ) {
			// some errors like port binding failed may not be assignable to a specific websocket
		}
	}

	@Override
	public void onStart() {
		System.out.println("Server started!");
		setConnectionLostTimeout(0);
		setConnectionLostTimeout(100);
	}
}
