Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

124
LINES

< > BotCompany Repo | #1001066 // startDialogServer etc.

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (11032L/63K).

static new AtomicInteger dialogServer_clients;
static boolean dialogServer_printConnects;
static new ThreadLocal<Bool> startDialogServer_quiet;

static Set<S> dialogServer_knownClients = synchroTreeSet();

static int startDialogServerOnPortAbove(int port, IDialogHandler handler) {
  while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler))
    ++port;
  return port;
}

static int startDialogServerOnPortAboveDaemon(int port, IDialogHandler handler) {
  while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true))
    ++port;
  return port;
}

static void startDialogServer(int port, IDialogHandler handler) {
  if (!startDialogServerIfPortAvailable(port, handler))
    fail("Can't start dialog server on port " + port);
}

static boolean startDialogServerIfPortAvailable(int port, final IDialogHandler handler) {
  return startDialogServerIfPortAvailable(port, handler, false);
}

static ServerSocket startDialogServer_serverSocket;
  
static boolean startDialogServerIfPortAvailable(int port, final IDialogHandler handler, boolean daemon) {
  ServerSocket serverSocket = null;
  try {
    serverSocket = new ServerSocket(port);
  } catch (IOException e) {
    // probably the port number is used - let's assume there already is a chat server.
    return false;
  }
  final ServerSocket _serverSocket = serverSocket;
  startDialogServer_serverSocket = serverSocket;

  Thread thread = new Thread("Socket accept port " + port) { public void run() {
   try {
    while (true) {
      try {
        final Socket s = _serverSocket.accept();
        
        S client = s.getInetAddress().toString();
        if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
          print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
          dialogServer_knownClients.add(client);
        }
        
        String threadName = "Handling client " + s.getInetAddress();

        Thread t2 = new Thread(threadName) {
         public void run() {
          try {
            final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
            final BufferedReader in = new BufferedReader(
              new InputStreamReader(s.getInputStream(), "UTF-8"));
              
            DialogIO io = new DialogIO() {
            
              // This should be the same as #1001076 (talkTo)
            
  boolean isLocalConnection() {
    return s.getInetAddress().isLoopbackAddress();
  }
  
  boolean isStillConnected() {
    return !(eos || s.isClosed());
  }
  
  void sendLine(String line) ctex {
    w.write(line + "\n");
    w.flush();
  }
  
  S readLineImpl() ctex {
    ret in.readLine();
  }
  
  public void close() {
    try {
      s.close();
    } catch (IOException e) {
      // whatever
    }
  }
  
  Socket getSocket() {
    return s;
  }
  };
            
            try {
              handler.run(io);
            } finally {
              if (!io.noClose)
                s.close();
            }
          } catch (IOException e) {
            print("[internal] " + e);
          } finally {
            //print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
          }
         }
        }; // Thread t2
        t2.setDaemon(true); // ?
        t2.start();
      } catch (SocketTimeoutException e) {
      }
    }   
   } catch (IOException e) {
     print("[internal] " + e);
   }
  }};
  if (daemon) thread.setDaemon(true);
  thread.start();
 
  if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet)))
    print("Dialog server on port " + port + " started."); 
  return true;
}

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1001066
Snippet name: startDialogServer etc.
Eternal ID of this version: #1001066/7
Text MD5: 4e13054297497ea711b6edec78673978
Transpilation MD5: bbbe1a21e488c420b31f9c5dd2d3ce52
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-05-28 23:10:19
Source code size: 3787 bytes / 124 lines
Pitched / IR pitched: No / No
Views / Downloads: 716 / 2824
Version history: 6 change(s)
Referenced in: #1002427 - Accellerating 629 (SPIKE)
#1006654 - Standard functions list 2 (LIVE, continuation of #761)
#3000382 - Answer for ferdie (>> t = 1, f = 0)
#3000383 - Answer for funkoverflow (>> t=1, f=0 okay)