1 /*******************************************************************************
\r
2 * Copyright (c) 2010 Association for Decentralized Information Management in
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.databoard.method;
14 import java.io.IOException;
\r
15 import java.net.ServerSocket;
\r
16 import java.net.Socket;
\r
17 import java.util.List;
\r
18 import java.util.concurrent.CopyOnWriteArrayList;
\r
19 import java.util.logging.Level;
\r
20 import java.util.logging.Logger;
\r
22 import org.simantics.databoard.method.TcpConnection.ConnectionListener;
\r
25 * Server opens a server socket and accepts incoming connections.
27 * Methods are invoked in read thread. Therefore method invocation blocks
29 * It is highly recommended that that MethodInterface implementation is
32 * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
36 static Logger LOGGER = Logger.getLogger(Server.class.getName());
40 MethodInterface handler;
41 List<TcpConnection> connections = new CopyOnWriteArrayList<TcpConnection>();
44 * Create new method interface server.
47 * @param handler method handler of local methods or
50 public Server(int port, MethodInterface handler)
53 this.handler = handler;
55 socket = new ServerSocket(port);
56 acceptThread = new Thread() {
63 } catch (IOException e) {
68 Handshake local = new Handshake();
69 local.methods = Server.this.handler.getInterface().getMethodDefinitions();
70 Handshake remote = TcpConnection.handshake(s, local);
71 final TcpConnection c = new TcpConnection(s, Server.this.handler, local, remote);
72 c.addConnectionListener(new ConnectionListener() {
74 public void onClosed() {
75 connections.remove(c);
78 public void onError(Exception error) {
79 connections.remove(c);
83 connections.add( c );
\r
84 if (c.getSocket().isClosed()) connections.remove(c);
85 } catch (IOException e) {
86 LOGGER.log(Level.FINER, "Connection Closed");
89 } catch (IOException e1) {
95 acceptThread.setDaemon(true);
100 * Stop listening for new connections and shutdown existing connections.
102 public void close() {
105 } catch (IOException e) {
107 for (TcpConnection c : connections) {
110 c.getSocket().close();
111 } catch (IOException e) {
117 * @return The port the server is listening.
\r
119 public int getPort() {
\r
120 return socket.getLocalPort();
\r