view samples/echo.tp @ 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
children
line wrap: on
line source

#{
	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"
		}
		
	}
}