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

70
LINES

< > BotCompany Repo | #1001076 - talkTo

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

Libraryless. Click here for Pure Java version (3596L/24K).

static DialogIO talkTo(int port) {
  return talkTo("localhost", port);
}

static int talkTo_defaultTimeout = 10000; // This is the CONNECT timeout
static int talkTo_timeoutForReads = 0; // Timeout waiting for answers (0 = no timeout)

static ThreadLocal<Map<S, DialogIO>> talkTo_byThread = new ThreadLocal;

static DialogIO talkTo(S ip, int port) ctex {
  S full = ip + ":" + port;
  Map<S, DialogIO> map = talkTo_byThread.get();
  if (map != null && map.containsKey(full)) ret map.get(full);
  
  if (isLocalhost(ip) && port == vmPort()) ret talkToThisVM();

  ret new talkTo_IO(ip, port);
}

sclass talkTo_IO extends DialogIO { 
  S ip;
  int port;
  Socket s;
  Writer w;
  BufferedReader in;
  
  *(S *ip, int *port) ctex {
    s = new Socket;
    try {
      if (talkTo_timeoutForReads != 0)
        s.setSoTimeout(talkTo_timeoutForReads);
      s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
    } catch (Throwable e) {
      fail("Tried talking to " + ip + ":" + port, e);
    }
  
    w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
    in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
  }
  
  boolean isLocalConnection() {
    return s.getInetAddress().isLoopbackAddress();
  }
  
  boolean isStillConnected() {
    return !(eos || s.isClosed());
  }
  
  void sendLine(String line) ctex {
    lock lock;
    w.write(line + "\n");
    w.flush();
  }
  
  S readLineImpl() ctex {
    ret in.readLine();
  }
  
  public void close() {
    try {
      if (!noClose) s.close();
    } catch (IOException e) {
      // whatever
    }
  }
  
  Socket getSocket() {
    return s;
  }
}

Author comment

Began life as a copy of #1000937

download  show line numbers  debug dex   

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

No comments. add comment

Snippet ID: #1001076
Snippet name: talkTo
Eternal ID of this version: #1001076/11
Text MD5: 46dd88aa4e2273eb2ee46fe8402736f0
Transpilation MD5: e0f505a630cc5e694510e61f3a8e8234
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-07-13 21:36:57
Source code size: 1714 bytes / 70 lines
Pitched / IR pitched: No / No
Views / Downloads: 585 / 5104
Version history: 10 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1001076 & http://1001076.tinybrain.de