-
-
Save nindalf/4836c45c857a3c431e38 to your computer and use it in GitHub Desktop.
Implementation of a scalable chat roulette program in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"net" | |
) | |
func main() { | |
socket, _ := net.Listen("tcp", "localhost:8080") | |
conns := make(chan io.ReadWriteCloser) | |
for { | |
conn, _ := socket.Accept() | |
go match(conn, conns) | |
} | |
} | |
func match(conn io.ReadWriteCloser, conns chan io.ReadWriteCloser) { | |
fmt.Fprint(conn, "Waiting for partner... ") | |
select { | |
case conns <- conn: | |
remoteConn := <-conns | |
startChat(conn, remoteConn) | |
case remoteConn := <-conns: | |
conns <- conn | |
startChat(conn, remoteConn) | |
} | |
} | |
func startChat(a, b io.ReadWriteCloser) { | |
fmt.Fprintln(a, "Found one!") | |
errc := make(chan error, 1) | |
go cp(a, b, errc) | |
go cp(b, a, errc) | |
if err := <-errc; err != nil { | |
} | |
a.Close() | |
b.Close() | |
} | |
func cp(a io.Reader, b io.Writer, errc chan error) { | |
_, err := io.Copy(b, a) | |
errc <- err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment