001 /**
002 * GRANITE DATA SERVICES
003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 * This file is part of the Granite Data Services Platform.
006 *
007 * ***
008 *
009 * Community License: GPL 3.0
010 *
011 * This file is free software: you can redistribute it and/or modify
012 * it under the terms of the GNU General Public License as published
013 * by the Free Software Foundation, either version 3 of the License,
014 * or (at your option) any later version.
015 *
016 * This file is distributed in the hope that it will be useful, but
017 * WITHOUT ANY WARRANTY; without even the implied warranty of
018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
019 * GNU General Public License for more details.
020 *
021 * You should have received a copy of the GNU General Public License
022 * along with this program. If not, see <http://www.gnu.org/licenses/>.
023 *
024 * ***
025 *
026 * Available Commercial License: GraniteDS SLA 1.0
027 *
028 * This is the appropriate option if you are creating proprietary
029 * applications and you are not prepared to distribute and share the
030 * source code of your application under the GPL v3 license.
031 *
032 * Please visit http://www.granitedataservices.com/license for more
033 * details.
034 */
035 package org.granite.gravity.udp;
036
037 import java.net.DatagramSocket;
038 import java.net.InetSocketAddress;
039
040 import org.granite.gravity.AbstractChannel;
041 import org.granite.gravity.udp.UdpReceiverFactory;
042 import org.granite.logging.Logger;
043
044 /**
045 * @author Franck WOLFF
046 */
047 public class UdpSharedIOChannelFactory extends AbstractUdpChannelFactory {
048
049 private static final Logger log = Logger.getLogger(UdpSharedIOChannelFactory.class);
050
051 private DatagramSocket socket = null;
052
053 public UdpSharedIOChannelFactory(UdpReceiverFactory factory) {
054 super(factory);
055 }
056
057 @Override
058 public void start() {
059 super.start();
060
061 int port = factory.getPort();
062
063 if (port == 0)
064 log.info("Creating shared UDP socket on port * (any available port)...");
065 else
066 log.info("Creating shared UDP socket on port %d...", port);
067
068 try {
069 socket = new DatagramSocket(port);
070 socket.setSendBufferSize(factory.getSendBufferSize());
071 }
072 catch (Exception e) {
073 throw new RuntimeException("Could not create data socket on port: " + port, e);
074 }
075
076 log.info("UDP shared socket bound to port: %d", socket.getLocalPort());
077 }
078
079 @Override
080 public void stop() {
081 super.stop();
082
083 log.info("Closing UDP socket...");
084
085 if (socket != null) {
086 try {
087 socket.close();
088 }
089 finally {
090 socket = null;
091 }
092 }
093
094 log.info("UDP socket closed.");
095 }
096
097 @Override
098 public UdpChannel newUdpChannel(AbstractChannel gravityChannel, InetSocketAddress address) {
099 return new UdpIOChannel(this, gravityChannel, socket, address);
100 }
101 }