本文整理汇总了Golang中net.UDPConn.ReadFrom方法的典型用法代码示例。如果您正苦于以下问题:Golang UDPConn.ReadFrom方法的具体用法?Golang UDPConn.ReadFrom怎么用?Golang UDPConn.ReadFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.UDPConn
的用法示例。
在下文中一共展示了UDPConn.ReadFrom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
go func() {
var addr net.Addr
var udp *net.UDPConn
var err error
if addr, err = net.ResolveUDPAddr("udp4", ":1234"); err != nil {
panic(err)
}
if udp, err = net.ListenUDP("udp", addr.(*net.UDPAddr)); err != nil {
panic(err)
}
var buf = make([]byte, 65535)
n, addr, e := udp.ReadFrom(buf)
if e != nil {
panic(e)
}
udp.WriteTo(buf[:n], addr)
}()
runtime.Gosched()
svr := NewPortalSvr()
svr.basAddr = "127.0.0.1:1234"
svr.basSecret = []byte("xxffe")
if err := svr.Listen(":1288"); err != nil {
panic(err)
}
svr.Run()
err := svr.Auth("aas", "asas1", "255.255.255.255:1223")
if err != nil {
println(err.Error())
}
}
示例2: serverRead
func serverRead(t *testing.T, server *net.UDPConn) string {
bytes := make([]byte, 1024)
n, _, err := server.ReadFrom(bytes)
if err != nil {
t.Fatal(err)
}
return string(bytes[:n])
}
示例3: readFromSessionUDP
// readFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a
// net.UDPAddr.
func readFromSessionUDP(conn *net.UDPConn, b []byte) (int, *sessionUDP, error) {
n, raddr, err := conn.ReadFrom(b)
if err != nil {
return n, nil, err
}
session := &sessionUDP{raddr.(*net.UDPAddr)}
return n, session, err
}
示例4: waitforudp
func waitforudp(conn *net.UDPConn, channel chan bool) {
message := make([]byte, maxUDPsize)
for { // ever...
n, remaddr, error := conn.ReadFrom(message)
checkError("Cannot read from", error)
go handleudp(conn, remaddr, message[0:n])
}
channel <- true
}
示例5: TestHandlePing
func TestHandlePing(t *testing.T) {
m := GetMemberlist(t)
m.config.EnableCompression = false
defer m.Shutdown()
var udp *net.UDPConn
for port := 60000; port < 61000; port++ {
udpAddr := fmt.Sprintf("127.0.0.1:%d", port)
udpLn, err := net.ListenPacket("udp", udpAddr)
if err == nil {
udp = udpLn.(*net.UDPConn)
break
}
}
if udp == nil {
t.Fatalf("no udp listener")
}
// Encode a ping
ping := ping{SeqNo: 42}
buf, err := encode(pingMsg, ping)
if err != nil {
t.Fatalf("unexpected err %s", err)
}
// Send
addr := &net.UDPAddr{IP: net.ParseIP(m.config.BindAddr), Port: m.config.BindPort}
udp.WriteTo(buf.Bytes(), addr)
// Wait for response
go func() {
time.Sleep(time.Second)
panic("timeout")
}()
in := make([]byte, 1500)
n, _, err := udp.ReadFrom(in)
if err != nil {
t.Fatalf("unexpected err %s", err)
}
in = in[0:n]
msgType := messageType(in[0])
if msgType != ackRespMsg {
t.Fatalf("bad response %v", in)
}
var ack ackResp
if err := decode(in[1:], &ack); err != nil {
t.Fatalf("unexpected err %s", err)
}
if ack.SeqNo != 42 {
t.Fatalf("bad sequence no")
}
}
示例6: Listen
func Listen(conn *net.UDPConn, incoming chan<- Packet) error {
for {
data := make([]byte, 8192)
size, remote, err := conn.ReadFrom(data)
if err != nil {
panic(err)
}
incoming <- Packet{data[0:size], remote}
}
}
示例7: udpEchoHandler
func udpEchoHandler(c *net.UDPConn) {
buf := make([]byte, 64)
for {
n, addr, err := c.ReadFrom(buf)
if err != nil {
return
}
if _, err = c.WriteTo(buf[0:n], addr); err != nil {
return
}
}
}
示例8: ReadUdpConnections
func ReadUdpConnections(conn *net.UDPConn) {
contexts := make(map[string]*UdpContext)
var buffer [1024]byte
for {
n, addr, err := conn.ReadFrom(buffer[:])
if err != nil {
log.Printf("Failed to read from udp socket: %s\n", err)
continue
}
key := addr.String()
context := contexts[key]
if context == nil {
// New request
message := string(buffer[:n])
context, err := CreateContext(addr, message)
if err != nil {
log.Printf("Failed to start udp session: %s\n", err)
continue
}
contexts[key] = context
// Start
if context.command == "get" {
HandleUdpGet(conn, context)
}
if context.command == "get" {
HandleUdpPut(conn, context)
}
} else if context.command == "get" {
message := string(buffer[:n])
// Flow-control: only allow one outstanding message at a time. Wait for an ack after every request.
if message != "get-ack" {
log.Println("Protocol error: expected get-ack")
continue
}
GetSend(conn, context)
} else if context.command == "put" {
message := string(buffer[:n])
context.length = context.length - PutRecv(conn, context)
}
}
}
示例9: recv
// recv is a long running routine to receive packets from an interface
func (s *Server) recv(c *net.UDPConn) {
if c == nil {
return
}
buf := make([]byte, 65536)
for !s.shouldShutdown {
n, from, err := c.ReadFrom(buf)
if err != nil {
continue
}
if err := s.parsePacket(buf[:n], from); err != nil {
log.Printf("[ERR] bonjour: Failed to handle query: %v", err)
}
}
}
示例10: Read
func (conn *Connection) Read(socket *net.UDPConn) {
b := make([]byte, defaultReadSize)
for {
n, addr, err := socket.ReadFrom(b)
conn.lastErr = err
if conn.IsError() {
close(conn.Datagrams)
break
}
conn.Datagrams <- Datagram{addr, b[0:n]}
}
}
示例11: TestIngestPacket_CRC
func TestIngestPacket_CRC(t *testing.T) {
m := GetMemberlist(t)
m.config.EnableCompression = false
defer m.Shutdown()
var udp *net.UDPConn
for port := 60000; port < 61000; port++ {
udpAddr := fmt.Sprintf("127.0.0.1:%d", port)
udpLn, err := net.ListenPacket("udp", udpAddr)
if err == nil {
udp = udpLn.(*net.UDPConn)
break
}
}
if udp == nil {
t.Fatalf("no udp listener")
}
// Get a message with a checksum
payload := []byte{3, 3, 3, 3}
m.rawSendMsgUDP(udp.LocalAddr(), &Node{PMax: 5}, payload)
in := make([]byte, 1500)
n, _, err := udp.ReadFrom(in)
if err != nil {
t.Fatalf("unexpected err %s", err)
}
in = in[0:n]
if len(in) != 9 {
t.Fatalf("bad: %v", in)
}
// Corrupt the checksum
in[1] <<= 1
logs := &bytes.Buffer{}
logger := log.New(logs, "", 0)
m.logger = logger
m.ingestPacket(in, udp.LocalAddr(), time.Now())
if !strings.Contains(logs.String(), "invalid checksum") {
t.Fatalf("bad: %s", logs.String())
}
}
示例12: multicastListen
//Called by MulticastInit
//All received messsages piped to buffered channel
func multicastListen(recv chan<- Message, conn *net.UDPConn) {
for {
buf := make([]byte, 512)
l, _, err := conn.ReadFrom(buf)
if err != nil {
fmt.Println("NET: ", err)
}
var m Message
err = json.Unmarshal(buf[:l], &m)
if err != nil {
fmt.Println("JSON unpacking: ", err)
} else {
m.TimeRecv = time.Now()
recv <- m
}
}
}
示例13: readAndWriteUDP
func readAndWriteUDP(r io.Reader, w io.Writer, con *net.UDPConn, ra net.Addr, verbose bool) <-chan net.Addr {
buf := make([]byte, BUFFER_LIMIT)
cAddr := make(chan net.Addr)
go func() {
defer func() {
con.Close()
cAddr <- ra
}()
for {
var bytesread int
var errRead, errWrite error
if con, ok := r.(*net.UDPConn); ok {
var addr net.Addr
bytesread, addr, errRead = con.ReadFrom(buf)
if con.RemoteAddr() == nil && ra == nil {
ra = addr
cAddr <- ra
}
} else {
bytesread, errRead = r.Read(buf)
}
if errRead != nil {
if errRead != io.EOF {
if verbose {
log.Println("READ ERROR: ", errRead)
}
}
break
}
if con, ok := w.(*net.UDPConn); ok && con.RemoteAddr() == nil {
_, errWrite = con.WriteTo(buf[0:bytesread], ra)
} else {
_, errWrite = w.Write(buf[0:bytesread])
}
if errWrite != nil {
if verbose {
log.Println("WRITE ERROR: ", errWrite)
}
return
}
}
}()
return cAddr
}
示例14: dnsListen
func dnsListen(conn net.UDPConn) {
buf := make([]byte, 1024)
n, addr, err := conn.ReadFrom(buf)
log.Print("Addr", addr)
if err != nil {
log.Fatal(err)
}
log.Printf("Data come in from: %s", addr)
reply := dnsRequest(buf[0:n])
_, err = conn.WriteTo(reply, addr)
if err != nil {
log.Fatal(err)
} else {
log.Print("=====EOF=====")
}
}
示例15: RunServerWithPacketHandler
//异步运行服务器,返回Closer以便可以关闭服务器,所有无法运行的错误panic出来,其他错误丢到kmgLog error里面.
func RunServerWithPacketHandler(address string, secret []byte, handler PacketHandler) func() error {
connChan := make(chan *net.UDPConn)
go func() {
var conn *net.UDPConn
addr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
panic(err)
}
conn, err = net.ListenUDP("udp", addr)
if err != nil {
panic(err)
}
connChan <- conn
for {
b := make([]byte, 4096)
n, senderAddress, err := conn.ReadFrom(b)
if err != nil {
panic(err)
}
go func(p []byte, senderAddress net.Addr) {
pac, err := DecodeRequestPacket(secret, p)
if err != nil {
kmgLog.Log("error", "radius.Decode", err.Error())
return
}
npac := handler(pac)
if npac == nil {
// 特殊情况,返回nil,表示抛弃这个包.
return
}
err = npac.Send(conn, senderAddress)
if err != nil {
kmgLog.Log("error", "radius.Send", err.Error())
return
}
}(b[:n], senderAddress)
}
return
}()
conn := <-connChan
close(connChan)
return conn.Close
}