本文整理汇总了Golang中net.UDPConn.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang UDPConn.Close方法的具体用法?Golang UDPConn.Close怎么用?Golang UDPConn.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.UDPConn
的用法示例。
在下文中一共展示了UDPConn.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: udp_transmit_server
func udp_transmit_server(lconn, bconn *net.UDPConn, send_ch chan Udp_message) {
defer func() {
if r := recover(); r != nil {
fmt.Println("ERROR in udp_transmit_server: %s \n Closing connection.", r)
lconn.Close()
bconn.Close()
}
}()
var err error
var n int
for {
// fmt.Printf("udp_transmit_server: waiting on new value on Global_Send_ch \n")
msg := <-send_ch
// fmt.Printf("Writing %s \n", msg.Data)
if msg.Raddr == "broadcast" {
n, err = lconn.WriteToUDP([]byte(msg.Data), baddr)
} else {
raddr, err := net.ResolveUDPAddr("udp", msg.Raddr)
if err != nil {
fmt.Printf("Error: udp_transmit_server: could not resolve raddr\n")
panic(err)
}
n, err = lconn.WriteToUDP([]byte(msg.Data), raddr)
}
if err != nil || n < 0 {
fmt.Printf("Error: udp_transmit_server: writing\n")
panic(err)
}
// fmt.Printf("udp_transmit_server: Sent %s to %s \n", msg.Data, msg.Raddr)
}
}
示例2: 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
}
}
}
示例3: udp_receive_server
func udp_receive_server(lconn, bconn *net.UDPConn, message_size int, receive_ch chan Udp_message) {
defer func() {
if r := recover(); r != nil {
fmt.Println("ERROR in udp_receive_server: %s \n Closing connection.", r)
lconn.Close()
bconn.Close()
}
}()
bconn_rcv_ch := make(chan Udp_message)
lconn_rcv_ch := make(chan Udp_message)
go udp_connection_reader(lconn, message_size, lconn_rcv_ch)
go udp_connection_reader(bconn, message_size, bconn_rcv_ch)
for {
select {
case buf := <-bconn_rcv_ch:
receive_ch <- buf
case buf := <-lconn_rcv_ch:
receive_ch <- buf
}
}
}
示例4: udpConnectionReader
/*
Used to listen for incoming UDP packets on an given connection. Runs an infinite loop reading from the connection to a buffer.
When a message is complete, it sends it to to the caller via the receive channel.
*/
func udpConnectionReader(connection *net.UDPConn, messageSize int, receiveChannel chan<- UDPMessage) {
defer func() {
if r := recover(); r != nil {
log.Println("UDPConnectionReader:\t ERROR in udpConnectionReader:\t %s \n Closig connection.", r)
connection.Close()
}
}()
for {
if debug {
log.Printf("UDPConnectionReader:\t Waiting on data from UDPConnection %s\n", connection.LocalAddr().String())
}
buffer := make([]byte, messageSize) // TODO: Do without allocation memory each time!
n, returnAddress, err := connection.ReadFromUDP(buffer)
if err != nil || n < 0 || n > messageSize {
log.Println("UDPConnectionReader:\t Error in ReadFromUDP:", err)
} else {
if debug {
log.Println("UDPConnectionReader:\t Received package from:", returnAddress.String())
log.Println("UDP-Listen:\t", string(buffer[:]))
}
receiveChannel <- UDPMessage{RAddress: returnAddress.String(), Data: buffer[:n], Length: n}
}
}
}
示例5: DialTunnel
func DialTunnel(addr string) (tc net.Conn, err error) {
var conn *net.UDPConn
var t *Tunnel
udpaddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return
}
conn, err = net.DialUDP("udp", nil, udpaddr)
if err != nil {
return
}
localaddr := conn.LocalAddr()
localstr := localaddr.String()
name := fmt.Sprintf("%s_cli", strings.Split(localstr, ":")[1])
t = NewTunnel(udpaddr, name, make(chan *SendBlock, TBUFSIZE))
c := &Client{t, conn, name, make(chan uint8)}
t.onclose = func() {
sutils.Info("close tunnel", localaddr)
conn.Close()
close(c.c_close)
close(t.c_send)
}
go c.sender()
go c.recver()
t.c_event <- EV_CONNECT
<-t.c_connect
sutils.Info("create tunnel", localaddr)
return &TunnelConn{t, localaddr}, nil
}
示例6: ServeUDP
func (srv *Server) ServeUDP(l *net.UDPConn) os.Error {
defer l.Close()
handler := srv.Handler
if handler == nil {
handler = DefaultServeMux
}
for {
m := make([]byte, DefaultMsgSize)
n, a, e := l.ReadFromUDP(m)
if e != nil {
return e
}
m = m[:n]
if srv.ReadTimeout != 0 {
l.SetReadTimeout(srv.ReadTimeout)
}
if srv.WriteTimeout != 0 {
l.SetWriteTimeout(srv.WriteTimeout)
}
d, err := newConn(nil, l, a, m, handler)
if err != nil {
continue
}
go d.serve()
}
panic("not reached")
}
示例7: main
func main() {
var (
addr *net.UDPAddr
listener *net.UDPConn
err error
)
log.LoadConfiguration(Conf.Log)
defer log.Close()
if addr, err = net.ResolveUDPAddr("udp4", Conf.Bind); err != nil {
log.Error("net.ResolveUDPAddr(\"udp4\", \"%s\") error(%v)", Conf.Bind, err)
return
}
if listener, err = net.ListenUDP("udp4", addr); err != nil {
log.Error("net.ListenUDP(\"udp4\", \"%v\") error(%v)", addr, err)
return
}
defer listener.Close()
if Debug {
log.Debug("start udp listen: \"%s\"", Conf.Bind)
}
//N core accept
for i := 0; i < Conf.MaxProc; i++ {
go acceptUDP(listener)
}
//wait
InitSignal()
}
示例8: listenLoop
// listenLoop wait request through a channel and send request and receive response.
func listenLoop(listenChan chan *ReqCommand, conn *net.UDPConn) {
defer conn.Close()
for {
reqCom := <-listenChan
n, err := send(reqCom.command, reqCom.dstAddr)
if err != nil || n == 0 {
log.Println("cannot write reqest: ", err, " bytes:", n)
continue
}
var buf []byte = make([]byte, 1500)
n, address, err := conn.ReadFromUDP(buf)
if err != nil {
log.Fatal(err)
}
if address != nil && n > 0 {
reqCom.ch <- buf[0:n]
} else {
log.Println("cannot read reqest: ", err, " bytes:", n)
reqCom.ch <- nil
}
}
}
示例9: NewNetInput
func NewNetInput(address string, port int) (*NetInput, error) {
var err error
var conn *net.UDPConn
n := &NetInput{}
n.addr = net.UDPAddr{
Port: port,
IP: net.ParseIP(address),
}
n.input = nil
// the stream may be unicast or multicast, so choose appropriately
if n.addr.IP.IsMulticast() {
conn, err = net.ListenMulticastUDP("udp", nil, &n.addr)
} else {
conn, err = net.ListenUDP("udp", &n.addr)
}
if err != nil {
conn.Close()
return nil, err
}
n.conn = conn
go n.process()
return n, nil
}
示例10: Run
func (local *localNode) Run(terminate <-chan bool) (err error) {
var conn *net.UDPConn
// Main loop for LocalPeer's activity.
// (Listening to replies and requests.)
conn, err = net.ListenUDP("udp4", &net.UDPAddr{
IP: net.IPv4(0, 0, 0, 0),
Port: local.Port,
})
if err != nil {
return
}
local.Connection = conn
rpcTerminate := make(chan bool)
go func() {
local.rpcListenLoop(rpcTerminate)
}()
go func() {
<-terminate
close(rpcTerminate)
conn.Close()
}()
return
}
示例11: Handshake
// Handshake performs data exchange between DHT client and server
func (dht *DHTClient) Handshake(conn *net.UDPConn) error {
// Handshake
var req DHTMessage
req.ID = "0"
req.Query = PacketVersion
req.Command = DhtCmdConn
// TODO: rename Port to something more clear
req.Arguments = fmt.Sprintf("%d", dht.P2PPort)
req.Payload = dht.NetworkHash
for _, ip := range dht.IPList {
req.Arguments = req.Arguments + "|" + ip.String()
}
var b bytes.Buffer
if err := bencode.Marshal(&b, req); err != nil {
Log(Error, "Failed to Marshal bencode %v", err)
conn.Close()
return err
}
// TODO: Optimize types here
msg := b.String()
if dht.Shutdown {
return nil
}
_, err := conn.Write([]byte(msg))
if err != nil {
Log(Error, "Failed to send packet: %v", err)
conn.Close()
return err
}
return nil
}
示例12: ServeUDP
// ServeUDP starts a UDP listener for the server.
// Each request is handled in a seperate goroutine,
// with the Handler set in ....
func (srv *Server) ServeUDP(l *net.UDPConn) error {
defer l.Close()
handler := srv.Handler
if handler == nil {
handler = DefaultServeMux
}
if srv.UDPSize == 0 {
srv.UDPSize = UDPMsgSize
}
for {
m := make([]byte, srv.UDPSize)
n, a, e := l.ReadFromUDP(m)
if e != nil {
return e
}
m = m[:n]
if srv.ReadTimeout != 0 {
l.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
}
if srv.WriteTimeout != 0 {
l.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
}
d, err := newConn(nil, l, a, m, handler, srv.TsigSecret)
if err != nil {
continue
}
go d.serve()
}
panic("not reached")
}
示例13: GetClientId
// Creates a 2 byte ClientID from the local machine's IP.
func GetClientId() (id []byte, err error) {
var conn *net.UDPConn
var addr *net.UDPAddr
// Connect to a random machine somewhere in this subnet. It's irrelevant
// where to, as long as it's not the loopback address.
if addr, err = net.ResolveUDPAddr("udp", "192.168.1.1:0"); err != nil {
return
}
if conn, err = net.DialUDP("udp", nil, addr); err != nil {
return
}
defer conn.Close()
// strip port number off.
str := conn.LocalAddr().String()
if idx := strings.LastIndex(str, ":"); idx != -1 {
str = str[0:idx]
}
var ip net.IP
if ip = net.ParseIP(str).To16(); ip == nil {
return
}
// TODO(jimt): I am unsure how 2 full IPv6 addresses in the same subnet relate
// to eachother. Specifically if the 2 last bytes in the 16-byte address are
// really the relevant bits that set them apart from eachother.
// For IPv4 this is simple: 192.168.2.101 vs 192.168.2.102 -> we need the
// '2.101' and '2.102' bits. Bytes are stored in Big Endian order.
id = []byte{ip[14], ip[15]}
return
}
示例14: udp_connection_closer
func udp_connection_closer(lconn, bconn *net.UDPConn) {
<-closeConnectionChan
handleOrders.ImConnected = false
fmt.Printf("%sDisconnected \n%s", def.ColR, def.ColN)
lconn.Close()
bconn.Close()
}
示例15: listenUdp
func listenUdp(c *net.UDPConn) {
//m := make(map[string]int, 100)
for {
var message string
buf := make([]byte, MAIN_BUFFER_SIZE)
n, addr, err := c.ReadFromUDP(buf)
if err != nil {
log.Fatalln("error reading UDP: ", err)
//break
}
message = string(buf[0:n])
log.Println("received message from ", addr, message)
writeSize, writeErr := c.WriteToUDP(buf, addr)
if writeErr != nil {
log.Fatalln("error writing UDP: ", writeErr, writeSize)
//break
}
// IF this is a chat message, broadcast it:
//h.broadcast <- message
// TODO: IF this is a movement command, hand it to nav system
// TODO: IF we don't recognize it, throw an error
}
c.Close()
}