Closed adzimzf closed 5 years ago
I try yamux here's my yamux client
package main import ( "log" "net" "strconv" "time" "github.com/hashicorp/yamux" ) func main() { addr := "127.0.0.1:3333" conn, _ := net.Dial("tcp", addr) // Setup client side of yamux session, err := yamux.Client(conn, nil) if err != nil { panic(err) } for i := 1; i <= 100; i++ { go testC(session, strconv.Itoa(i)) } time.Sleep(60 * time.Second) conn.Close() } func testC(session *yamux.Session, st string) { // Open a new stream stream, err := session.Open() if err != nil { panic(err) } // stream.SetDeadline(time.Now().Add(3)) _, err = stream.Write([]byte(st)) if err != nil { panic(err) } reply := make([]byte, 7000) _, err = stream.Read(reply) if err != nil { panic(err) } log.Println("STRING " + st + ":" + string(reply)) }
and here's my server
package main import ( "bufio" "fmt" "log" "net" ) func handleConnection(conn net.Conn) { fmt.Println("Handling new connection...") // Close connection when this function ends defer func() { fmt.Println("Closing connection...") conn.Close() }() // timeoutDuration := 5 * time.Second bufReader := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)) for { // Set a deadline for reading. Read operation will fail if no data // is received after deadline. // conn.SetWriteDeadline(time.Now().Add(timeoutDuration)) // Read tokens delimited by newline bytes, err := bufReader.ReadString('\n') if err != nil { fmt.Println(err) return } _, err = bufReader.WriteString(bytes) if err != nil { log.Println(err) return } err = bufReader.Flush() if err != nil { log.Println("Flush failed.", err) } if string(bytes) == "exit" { log.Println("should be exit") conn.Close() } fmt.Printf("%s", bytes) } } func main() { // Start listening to port 3333 for TCP connection listener, err := net.Listen("tcp", ":3333") if err != nil { fmt.Println(err) return } defer func() { listener.Close() fmt.Println("Listener closed") }() for { // Get net.TCPConn object conn, err := listener.Accept() if err != nil { fmt.Println(err) break } go handleConnection(conn) } }
but why it can't send message to server? is both server and client should implement yamux? or any issue on my code? Thanks
You need yamux both in sever and client.
I try yamux here's my yamux client
and here's my server
but why it can't send message to server? is both server and client should implement yamux? or any issue on my code? Thanks