Skip to content

Instantly share code, notes, and snippets.

@aturley
Created April 3, 2018 13:31
Show Gist options
  • Save aturley/4a35a46c50b16087999d98f5b41bb80b to your computer and use it in GitHub Desktop.
Save aturley/4a35a46c50b16087999d98f5b41bb80b to your computer and use it in GitHub Desktop.
Basic TCP chat server in Pony
use "net"
actor ConnectionHub
let _connections: Array[TCPConnection] = Array[TCPConnection]
be add(conn: TCPConnection) =>
_connections.push(conn)
be remove(conn: TCPConnection) =>
try _connections.remove(_connections.find(conn)?, 1) end
be send(message: Array[U8] val, exclude_connection: TCPConnection) =>
for c in _connections.values() do
if c isnt exclude_connection then
c.write(message)
end
end
class HelloConnectionNotify is TCPConnectionNotify
let _connections: ConnectionHub
new iso create(connections: ConnectionHub) =>
_connections = connections
fun ref accepted(conn: TCPConnection ref) =>
_connections.add(conn)
fun ref received(
conn: TCPConnection ref,
data: Array[U8] iso,
times: USize)
: Bool
=>
_connections.send(consume data, conn)
true
fun ref closed(conn: TCPConnection ref) =>
_connections.remove(conn)
fun ref connect_failed(conn: TCPConnection ref) =>
None
class HelloListenNotify is TCPListenNotify
let _connections: ConnectionHub = ConnectionHub
fun ref connected(listen: TCPListener ref): TCPConnectionNotify iso^ =>
HelloConnectionNotify(_connections)
fun ref not_listening(listen: TCPListener ref) =>
None
actor Main
new create(env: Env) =>
env.out.print("hello world")
try
TCPListener(env.root as AmbientAuth,
HelloListenNotify, "", "8989")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment