Communicating with external applications over TCP/IP socket /websockets using gateway scripts

Just call all the java stuff from jython. Use jython’s NetBeans shorthand where you can.
Something like this (ultra-simplified):

from java.net import InetSocketAddress
from java.nio import ByteBuffer
from java.nio.channels import SocketChannel
from java.nio.charset import StandardCharsets

def opener(target):
	parts = target.rsplit(':', 1)
	if len(parts)>1:
		print "Socket Address %s:%s" % (parts[0], parts[1])
		sa = InetSocketAddress(parts[0], int(parts[1]))
	else:
		print "Socket Address %s Default Port 1234" % parts[0]
		sa = InetSocketAddress(parts[0], 1234)
	ch=SocketChannel.open()
	ch.connect(sa)
	# Save channel somewhere for the write thread
	# Set up a message queue and start writer.
	shared.later.callAsync(writer, ch, mq)
	bb=ByteBuffer.allocate(4096)
	while True:
		ch.read(bb)
		# extract and dispatch message(s) or loop for more

def writer(ch, mq):
	while True:
		msg = mq.pop()
		bb = StandardCharsets.UTF_8.encode(msg + "\r\n")
		ch.write(bb)

You’ll have to work out blocking vs. nonblocking as needed to find message boundaries, and possibly have some form of state machine or request tracking map to match up requests and replies. Some things you might want to do will be simpler with Streams instead of ByteBuffers. You might also want to use java.nio instead of java.net.

1 Like