本文整理汇总了Golang中net.UDPConn.Read方法的典型用法代码示例。如果您正苦于以下问题:Golang UDPConn.Read方法的具体用法?Golang UDPConn.Read怎么用?Golang UDPConn.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.UDPConn
的用法示例。
在下文中一共展示了UDPConn.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: assertServerMatchesExpected
func assertServerMatchesExpected(t *testing.T, server *net.UDPConn, buf []byte, expected string) {
n, _ := server.Read(buf)
msg := buf[:n]
if string(msg) != expected {
t.Fatalf("Line %s does not match expected: %s", string(msg), expected)
}
}
示例2: UDPreadFromSocket
// Returns a string of the socketreading
func UDPreadFromSocket(listenSock *net.UDPConn) (listenstring string, err error) {
listenbuffer := make([]byte, 1024)
antall, err := listenSock.Read(listenbuffer)
listenstring = Trim(string(listenbuffer[0:antall]), "\x00")
return listenstring, err
}
示例3: retrieveFortune
func retrieveFortune(clientConn net.UDPConn, fortuneInfoMsg clientServerUtils.FortuneInfoMessage) clientServerUtils.FortuneMessage {
//Send FortuneReqMessage to fserver
fortuneReqMsg := clientServerUtils.FortuneReqMessage{fortuneInfoMsg.FortuneNonce}
fortuneReq, err := json.Marshal(fortuneReqMsg)
if err != nil {
fmt.Println("Error marshalling fortuneReqMsg: ", err)
os.Exit(-1)
}
fmt.Println("Retrieving fortune from fserver")
fserverUDPAddr := resolveUDPAddr(fortuneInfoMsg.FortuneServer)
_, err = clientConn.WriteToUDP(fortuneReq, &fserverUDPAddr)
if err != nil {
fmt.Println("Error writing to fserver: ", err)
os.Exit(-1)
}
//Receive FortuneMessage reply from fserver
var buf [1024]byte
msgLen, err := clientConn.Read(buf[:])
if err != nil {
fmt.Println("Error on read: ", err)
os.Exit(-1)
}
fortuneReplyStr := string(buf[0:msgLen])
fortuneBytes := []byte(fortuneReplyStr)
var fortune clientServerUtils.FortuneMessage
json.Unmarshal(fortuneBytes, &fortune)
return fortune
}
示例4: ListenForDsPackets
// Loops indefinitely to read packets and update connection status.
func ListenForDsPackets(listener *net.UDPConn) {
var data [50]byte
for {
listener.Read(data[:])
dsStatus := decodeStatusPacket(data)
// Update the status and last packet times for this alliance/team in the global struct.
dsConn := mainArena.AllianceStations[dsStatus.AllianceStation].DsConn
if dsConn != nil && dsConn.TeamId == dsStatus.TeamId {
dsConn.DriverStationStatus = dsStatus
dsConn.LastPacketTime = time.Now()
if dsStatus.RobotLinked {
dsConn.LastRobotLinkedTime = time.Now()
}
dsConn.SecondsSinceLastRobotLink = time.Since(dsConn.LastRobotLinkedTime).Seconds()
dsConn.DriverStationStatus.MissedPacketCount -= dsConn.missedPacketOffset
// Log the packet if the match is in progress.
matchTimeSec := mainArena.MatchTimeSec()
if matchTimeSec > 0 && dsConn.log != nil {
dsConn.log.LogDsStatus(matchTimeSec, dsStatus)
}
}
}
}
示例5: recv
// recv is used to receive until we get a shutdown
func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) {
if l == nil {
return
}
buf := make([]byte, 65536)
var closed bool
for {
c.closeLock.RLock()
closed = c.closed
c.closeLock.RUnlock()
if closed {
break
}
n, err := l.Read(buf)
if err != nil {
Log.Printf("[ERR] mdns: Failed to read packet: %v", err)
continue
}
msg := new(dns.Msg)
if err := msg.Unpack(buf[:n]); err != nil {
Log.Printf("[ERR] mdns: Failed to unpack packet: %v", err)
continue
}
select {
case msgCh <- msg:
case <-c.closedCh:
return
}
}
}
示例6: read
func read(s *net.UDPConn) {
b := make([]byte, 256)
for {
n, e := s.Read(b)
if e != nil {
log.Fatalf("Error reading from socket: %s", e)
}
parts := strings.Split(string(b[0:n]), "\t")
f, ferr := strconv.ParseFloat(parts[2], 64)
if ferr != nil {
log.Printf("Error parsing float: %s", ferr)
continue
}
t, terr := time.Parse(timeInFormat, strings.Split(parts[0], ".")[0])
if terr != nil {
log.Printf("Error parsing time: %s", terr)
continue
}
// Do this to convert to UTC
// t = time.SecondsToUTC(t.Seconds() - int64(time.LocalTime().ZoneOffset))
record := reading{
when: t,
sensor: parts[1],
reading: f,
}
readingsSingleton.input <- record
}
}
示例7: PutRecv
func PutRecv(conn *net.UDPConn, context *UdpContext) int {
file := context.file
buffer := make([]byte, 1024)
read, err := conn.Read(buffer)
if err == io.EOF {
break
}
if err != nil {
fmt.Printf("Error reading from network: %s. Aborting transfer\n", err)
return
}
_, err = file.Write(buffer[:read])
if err != nil {
fmt.Println("Error writing to file; aborting transfer")
return
}
_, err = conn.Write([]byte("put-ack"))
if err != nil {
fmt.Println("Error writing ack; aborting transfer")
return
}
return read
}
示例8: replyLoop
func (proxy *UDPProxy) replyLoop(proxyConn *net.UDPConn, clientAddr *net.UDPAddr, clientKey *connTrackKey) {
defer func() {
proxy.connTrackLock.Lock()
delete(proxy.connTrackTable, *clientKey)
proxy.connTrackLock.Unlock()
proxyConn.Close()
}()
readBuf := make([]byte, UDPBufSize)
for {
proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
again:
read, err := proxyConn.Read(readBuf)
if err != nil {
if err, ok := err.(*net.OpError); ok && err.Err == syscall.ECONNREFUSED {
// This will happen if the last write failed
// (e.g: nothing is actually listening on the
// proxied port on the container), ignore it
// and continue until UDPConnTrackTimeout
// expires:
goto again
}
return
}
for i := 0; i != read; {
written, err := proxy.listener.WriteToUDP(readBuf[i:read], clientAddr)
if err != nil {
return
}
i += written
}
}
}
示例9: receiveUDP
func receiveUDP(udpConn *net.UDPConn, ch chan []byte, queueSize *int32) {
bytes := make([]byte, maxMessageSize)
read, err := udpConn.Read(bytes)
for err == nil {
atomic.AddInt32(queueSize, 1)
ch <- bytes[:read]
bytes = make([]byte, maxMessageSize)
read, err = udpConn.Read(bytes)
}
}
示例10: start
func (l *Listener) start(conn *net.UDPConn) {
for {
buff := make([]byte, 2048)
n, err := conn.Read(buff)
if err != nil {
log.Println(err)
}
secret, Lpos, err := getSecret(buff[0:n])
if err != nil {
continue
}
if l.print {
log.Println(string(buff[0 : n-1]))
}
l.mapMu.RLock()
source, ok := l.sources[secret]
l.mapMu.RUnlock()
if !ok {
continue
}
go func() {
if atomic.LoadInt32(source.closed) == 1 {
return
}
handler := source.handler
if source.test {
l.mapMu.Lock()
delete(l.sources, source.Secret)
l.mapMu.Unlock()
atomic.StoreInt32(source.closed, 1)
handler.success <- struct{}{}
source.rcon.StopLogRedirection(l.redirectAddr)
source.rcon.Close()
return
}
source.logsMu.Lock()
source.logs.Write(buff[Lpos : n-1])
source.logsMu.Unlock()
m := ParseLogEntry(string(buff[Lpos : n-2]))
m.Parsed.CallHandler(handler)
}()
}
}
示例11: opusReceiver
// opusReceiver listens on the UDP socket for incoming packets
// and sends them across the given channel
// NOTE :: This function may change names later.
func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
if udpConn == nil || close == nil {
return
}
p := Packet{}
recvbuf := make([]byte, 1024)
var nonce [24]byte
for {
rlen, err := udpConn.Read(recvbuf)
if err != nil {
// Detect if we have been closed manually. If a Close() has already
// happened, the udp connection we are listening on will be different
// to the current session.
v.RLock()
sameConnection := v.udpConn == udpConn
v.RUnlock()
if sameConnection {
v.log(LogError, "udp read error, %s, %s", v.endpoint, err)
v.log(LogDebug, "voice struct: %#v\n", v)
go v.reconnect()
}
return
}
select {
case <-close:
return
default:
// continue loop
}
// For now, skip anything except audio.
if rlen < 12 || recvbuf[0] != 0x80 {
continue
}
// build a audio packet struct
p.Type = recvbuf[0:2]
p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
// decrypt opus data
copy(nonce[:], recvbuf[0:12])
p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
if c != nil {
c <- &p
}
}
}
示例12: readInputUdp
// readInputUdp parses the buffer for UDP sockets.
func readInputUdp(conn net.UDPConn, parseChannel chan []byte, logger Logger, config *ConfigValues) {
// config.Connection.Udp.Maxpacket is our max read
// Large buffer to handle high UDP traffic, and manage GC pressure
bufSize := 1 << 20
buf := make([]byte, bufSize)
offset := 0
flush := func() []byte {
parseChannel <- buf[0:offset]
offset = 0
return make([]byte, bufSize)
}
// Set initial deadline: 500ms
sockErr := conn.SetDeadline(time.Now().Add(time.Millisecond * 500))
if sockErr != nil {
logger.Error.Printf("Error seting socket deadline: %s", sockErr)
panic(sockErr)
}
for {
length, err := conn.Read(buf[offset : offset+config.Connection.Udp.Maxpacket])
if err == nil {
// Always delimit our metrics
buf[offset+length] = '\n'
offset = offset + length + 1
} else if terr, ok := err.(net.Error); ok && terr.Timeout() {
if offset > 0 {
buf = flush()
}
sockErr = conn.SetDeadline(time.Now().Add(time.Millisecond * 500))
if sockErr != nil {
panic(sockErr)
}
} else if strings.HasSuffix(err.Error(), "use of closed network connection") {
// Go, it would be great if there was a better way to detect
// this error...an enum?
// Connection closed, lets wrap up and finish
logger.Info.Printf("Stopping UDP read goroutine.")
return
} else {
logger.Error.Println("UDP read error:", err)
}
// Full Buffer?
if bufSize-offset <= config.Connection.Udp.Maxpacket {
buf = flush()
}
// Track the number of UDP packets we read
UdpPackets++
}
}
示例13: ListenAndWrite
// ListenAndWrite listens on the provided UDP address, parses the received
// packets and writes them to the provided api.Writer.
func (srv *Server) ListenAndWrite() error {
addr := srv.Addr
if addr == "" {
addr = ":" + DefaultService
}
laddr, err := net.ResolveUDPAddr("udp", srv.Addr)
if err != nil {
return err
}
var sock *net.UDPConn
if laddr.IP != nil && laddr.IP.IsMulticast() {
var ifi *net.Interface
if srv.Interface != "" {
if ifi, err = net.InterfaceByName(srv.Interface); err != nil {
return err
}
}
sock, err = net.ListenMulticastUDP("udp", ifi, laddr)
} else {
sock, err = net.ListenUDP("udp", laddr)
}
if err != nil {
return err
}
defer sock.Close()
if srv.BufferSize <= 0 {
srv.BufferSize = DefaultBufferSize
}
buf := make([]byte, srv.BufferSize)
popts := ParseOpts{
PasswordLookup: srv.PasswordLookup,
SecurityLevel: srv.SecurityLevel,
}
for {
n, err := sock.Read(buf)
if err != nil {
return err
}
valueLists, err := Parse(buf[:n], popts)
if err != nil {
log.Printf("error while parsing: %v", err)
continue
}
go dispatch(valueLists, srv.Writer)
}
}
示例14: Run
func (us *UDPSource) Run(l *net.UDPConn) {
// Why doesn't this get called on ctrl + c
var buf [1024]byte
for {
n, err := l.Read(buf[0:])
if err != nil || n == 0 {
break
}
us.data <- pipe.NewSimpleChunk(buf[0:n])
}
}
示例15: readUDP
// FIXME: 注意 conn 对象被多个goroutine 持有了,
func (client *UdpClient) readUDP(conn *net.UDPConn) {
var err error
defer func() {
if err := recover(); nil != err {
client.ERROR.Print("[panic]", client.logCtx, " read udp failed,", err)
}
conn.Close()
atomic.StoreInt32(&client.conn_ok, 0)
}()
for 0 == atomic.LoadInt32(&client.is_closed) {
var length int
var bs []byte
client.cached_rlock.Lock()
bs = client.cached_readBytes
client.cached_readBytes = nil
client.cached_rlock.Unlock()
if nil == bs {
bs = newCachedBytes()
}
if client.DEBUG.IsEnabled() {
client.DEBUG.Print(client.logCtx, "begin read pdu - ", len(bs))
}
length, err = conn.Read(bs)
if 0 != atomic.LoadInt32(&client.is_closed) {
break
}
if 10 > length {
continue
}
if nil != err {
client.cached_rlock.Lock()
client.conn_error = err
client.cached_rlock.Unlock()
client.ERROR.Print(client.logCtx, "read udp from conn failed", err)
break
}
if client.DEBUG.IsEnabled() {
client.DEBUG.Print(client.logCtx, "read pdu ok - ", hex.EncodeToString(bs[:length]))
}
client.bytes_c <- bytesRequest{cached: bs, length: length}
}
client.ERROR.Print(client.logCtx, "read udp is exited.")
}