4267a229创建于 2024年8月2日历史提交
/*
    Copyright (c) [2023] [squallzhao]
    fountain is licensed under APACHE LICENSE, VERSION 2.0.
    You can use this software according to the terms and conditions of the APACHE LICENSE, VERSION 2.0.
    You may obtain a copy of APACHE LICENSE, VERSION 2.0 at: https://www.apache.org/licenses/LICENSE-2.0
*/
package microservice.web.socket
import std.sync.*
import microservice.common.*

public class EndPoint {
    var port: UInt16 = 80 
    var acceptor: Acceptor;
    var handler: SocketHandler;
    let defaultMaxConnections :Int32 = 10000
    var connectionCounter: AtomicInt32 = AtomicInt32(defaultMaxConnections);
    var maxConnections: Int32 = 0

    public init(dataprocessor: IDataProcessor){
        this.acceptor = Acceptor(this.port);
        this.handler = SocketHandler(dataprocessor);
    }

    public init(port: UInt16, dataprocessor: IDataProcessor){
        this.port = port;
        this.acceptor = Acceptor(this.port);
        this.handler = SocketHandler(dataprocessor);
    }

    public func setMaxConnections(c: Int32){
        maxConnections = c
        if (maxConnections > 0){
            connectionCounter = AtomicInt32(c);
        }
    }

    public func start():Unit{
        if (maxConnections>0){
            var total = connectionCounter.fetchSub(1)
            while( total <=0){
                Common.sleepms(10)
                total = connectionCounter.load() + 1
            }
        }
       
        let socket = acceptor.accept();
        spawn{
            try{
                handler.run(socket);
            } finally{
                if (maxConnections>0){
                    connectionCounter.fetchAdd(1)
                }
            }
        }
        spawn{
            start()
        }
    }

    public func stop():Unit{
        acceptor.stop()
    }
}