Changeset

3003:48871a549b4c

net.server_select, net.server_event: Add server.link() to link 2 connections with an intermediate buffer of the specified size
author Matthew Wild <mwild1@gmail.com>
date Wed, 05 May 2010 15:25:48 +0100
parents 3002:d1f864ed44c0
children 3004:c20b9fe1624b
files net/server_event.lua net/server_select.lua
diffstat 2 files changed, 44 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/net/server_event.lua	Wed May 05 15:24:24 2010 +0100
+++ b/net/server_event.lua	Wed May 05 15:25:48 2010 +0100
@@ -845,11 +845,32 @@
 	return signal_events[signal_num];
 end
 
+local function link(sender, receiver, buffersize)
+	sender:set_mode(buffersize);
+	local sender_locked;
+	
+	function receiver:ondrain()
+		if sender_locked then
+			sender:resume();
+			sender_locked = nil;
+		end
+	end
+	
+	function sender:onincoming(data)
+		receiver:write(data);
+		if receiver.writebufferlen >= buffersize then
+			sender_locked = true;
+			sender:pause();
+		end
+	end
+end
+
 return {
 
 	cfg = cfg,
 	base = base,
 	loop = loop,
+	link = link,
 	event = event,
 	event_base = base,
 	addevent = newevent,
--- a/net/server_select.lua	Wed May 05 15:24:24 2010 +0100
+++ b/net/server_select.lua	Wed May 05 15:25:48 2010 +0100
@@ -675,6 +675,28 @@
 	--mem_free( )
 end
 
+local function link(sender, receiver, buffersize)
+	sender:set_mode(buffersize);
+	local sender_locked;
+	local _sendbuffer = receiver.sendbuffer;
+	function receiver.sendbuffer()
+		_sendbuffer();
+		if sender_locked and receiver.bufferlen() < buffersize then
+			sender:lock_read(false); -- Unlock now
+			sender_locked = nil;
+		end
+	end
+	
+	local _readbuffer = sender.readbuffer;
+	function sender.readbuffer()
+		_readbuffer();
+		if not sender_locked and receiver.bufferlen() >= buffersize then
+			sender_locked = true;
+			sender:lock_read(true);
+		end
+	end
+end
+
 ----------------------------------// PUBLIC //--
 
 addserver = function( addr, port, listeners, pattern, sslctx ) -- this function provides a way for other scripts to reg a server
@@ -898,6 +920,7 @@
 	wrapclient = wrapclient,
 	
 	loop = loop,
+	link = link,
 	stats = stats,
 	closeall = closeall,
 	addtimer = addtimer,