xtaci / kcp-go

A Crypto-Secure Reliable-UDP Library for golang with FEC
MIT License
4.12k stars 737 forks source link

链接断了无法重连 #195

Closed zhaopengme closed 3 years ago

zhaopengme commented 3 years ago

官方的例子,拆分了一下,如果把 server.go或者client.go 任何一个重新启动一次,就无法接受不到消息了

server.go

package main

import (
    "github.com/xtaci/kcp-go/v5"
    "log"
)

func main() {
    if listener, err := kcp.ListenWithOptions("127.0.0.1:12345", nil, 10, 3); err == nil {
        for {
            s, err := listener.AcceptKCP()
            if err != nil {
                log.Fatal(err)
            }
            handleEcho(s)
        }
    } else {
        log.Fatal(err)
    }
}

// handleEcho send back everything it received
func handleEcho(conn *kcp.UDPSession) {
    buf := make([]byte, 4096)
    for {
        n, err := conn.Read(buf)
        if err != nil {
            log.Println(err)
            return
        }

        log.Println(string(buf[:n]))
    }
}

client.go

package main

import (
    "log"
    "time"

    "github.com/xtaci/kcp-go/v5"
)

func main() {

    // dial to the echo server
    if sess, err := kcp.DialWithOptions("127.0.0.1:12345", nil, 10, 3); err == nil {
        for {
            data := time.Now().String()
            log.Println("sent:", data)
            if _, err := sess.Write([]byte(data)); err == nil {
            } else {
                log.Fatal(err)
            }
            time.Sleep(time.Second)
        }
    } else {
        log.Fatal(err)
    }
}
xtaci commented 3 years ago

应用层做超时处理