Created
September 25, 2013 18:06
-
-
Save rafkhan/6703563 to your computer and use it in GitHub Desktop.
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 ( | |
"net" | |
"fmt" | |
"bufio" | |
) | |
var ( | |
inboundQueue = make(chan net.Conn); | |
) | |
func main() { | |
quit := make(chan bool); | |
go acceptConn(); //start listening | |
go handleInbound(); //handle conn in goroutine | |
<-quit; | |
} | |
//Endless Accept() loop on given Listener | |
func acceptConn() { | |
ln, err := net.Listen("tcp", ":8080") | |
if err != nil { | |
// handle error | |
fmt.Println(err); | |
} | |
fmt.Println("Accepting"); | |
for { | |
conn, err := ln.Accept() | |
if err != nil { | |
fmt.Println(err); | |
continue | |
} | |
inboundQueue <- conn; | |
} | |
} | |
//Handle inbound connections on queue | |
func handleInbound() { | |
for { | |
c1 := <-inboundQueue; | |
c2 := <-inboundQueue; | |
go initiateP2P(c1, c2); | |
} | |
} | |
func initiateP2P(c1 net.Conn, c2 net.Conn) { | |
quit := make(chan bool); | |
fmt.Println("Init p2p"); | |
msgRW := func(in net.Conn, out net.Conn) { | |
defer in.Close(); | |
inMsg := make(chan string); | |
go func() { | |
for { | |
line, _ := bufio.NewReader(in).ReadString('\n') | |
out.Write([]byte(line)); | |
} | |
}(); | |
<-inMsg; | |
} | |
go msgRW(c1, c2); | |
go msgRW(c2, c1); | |
for { <-quit; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment