changeset 371:625b0aa9c204

Add a simple echo server sample to demonstrate socket listening
author Michael Pavone <pavone@retrodev.com>
date Wed, 12 Aug 2015 19:13:52 -0700
parents 57d78a0af132
children e857104bd183
files samples/echo.tp
diffstat 1 files changed, 33 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/samples/echo.tp	Wed Aug 12 19:13:52 2015 -0700
@@ -0,0 +1,33 @@
+#{
+	echo <- :sock {
+		print: "New connection\n"
+		data <- sock recv: 4096
+		while: { (data length) > 0 } do: {
+			sock send: data
+			data <- sock recv: 4096
+		}
+		print: "Connection closed\n"
+	}
+	
+	main <- :args {
+		port <- "2323"
+		if: (args length) > 1 {
+			port <- args get: 1
+		}
+		(socket listenOnPort: port) value: :lsock {
+			print: "Listening on port " . port . "\n"
+			continue? <- true
+			while: { continue? } do: {
+				(lsock accept) value: :csock {
+					echo: csock
+				} none: {
+					print: "Failed to accept new connection\n"
+					continue? <- false
+				}
+			}
+		} none: {
+			print: "Failed to listen on port " . port . "\n"
+		}
+		
+	}
+}
\ No newline at end of file