本文整理汇总了Golang中net.PacketConn.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang PacketConn.Close方法的具体用法?Golang PacketConn.Close怎么用?Golang PacketConn.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.PacketConn
的用法示例。
在下文中一共展示了PacketConn.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: echoServer
func echoServer(Address *string, Message *string) {
var c net.PacketConn
var err error
c, err = net.ListenPacket("sctp", *settings.Address)
if err != nil {
log.Printf("Error listening: %v", err)
os.Exit(-1)
}
defer c.Close()
for {
msg := make([]byte, 2048)
log.Printf("Listening on %s", *settings.Address)
_, addr, err := c.ReadFrom(msg)
if err != nil {
log.Printf("Error: %v ", err)
break
}
fmt.Println("Message: " + string(msg))
c.WriteTo(msg, addr)
}
}
示例2: packetEcho
func packetEcho(c net.PacketConn) {
defer c.Close()
buf := make([]byte, 65536)
for {
n, addr, err := c.ReadFrom(buf)
if err != nil {
return
}
if _, err := c.WriteTo(buf[:n], addr); err != nil {
return
}
}
}
示例3: runUdpReader
func runUdpReader(c net.PacketConn, msgChan chan<- string) {
var buf [4096]byte
var rcvd string = ""
for {
n, _, err := c.ReadFrom(buf[0:])
if err != nil || n == 0 {
break
}
rcvd += string(buf[0:n])
}
msgChan <- rcvd
c.Close()
}
示例4: Receive
// Receive accepts incoming datagrams on c and calls r.Handler.HandleMetric() for each line in the
// datagram that successfully parses in to a Metric
func (r *MetricReceiver) Receive(c net.PacketConn) error {
defer c.Close()
msg := make([]byte, 1024)
for {
nbytes, addr, err := c.ReadFrom(msg)
if err != nil {
log.Printf("%s", err)
continue
}
buf := make([]byte, nbytes)
copy(buf, msg[:nbytes])
go r.handleMessage(addr, buf)
}
panic("not reached")
}
示例5: Serve
// Serve accepts incoming connections ARP requests on net.PacketConn p,
// creating a new goroutine for each.
//
// The service goroutine reads requests, generates the appropriate Request and
// ResponseSender values, then calls s.Handler to handle the request.
func (s *Server) Serve(p net.PacketConn) error {
defer p.Close()
// Loop and read requests until exit
buf := make([]byte, 128)
for {
n, addr, err := p.ReadFrom(buf)
if err != nil {
// Treat EOF as an exit signal
if err == io.EOF {
return nil
}
return err
}
c := s.newConn(p, addr.(*raw.Addr), n, buf)
go c.serve()
}
}
示例6: echoServer
func echoServer(Address *string, Message *string) {
var c net.PacketConn
var err error
c, err = net.ListenPacket("sctp", *settings.Address)
if err != nil {
log.Printf("Error listening: %v", err)
os.Exit(-1)
}
defer c.Close()
log.Printf("Listening on %s", *settings.Address)
msg := make([]byte, 2048)
for {
_, _, err := c.ReadFrom(msg)
if err != nil {
log.Printf("Error: %v ", err)
break
}
}
}
示例7: runPktSyslog
func runPktSyslog(c net.PacketConn, done chan<- string) {
var buf [4096]byte
var rcvd string
ct := 0
for {
var n int
var err error
c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
n, _, err = c.ReadFrom(buf[:])
rcvd += string(buf[:n])
if err != nil {
if oe, ok := err.(*net.OpError); ok {
if ct < 3 && oe.Temporary() {
ct++
continue
}
}
break
}
}
c.Close()
done <- rcvd
}
示例8:
origin := []string{"test-origin"}
BeforeEach(func() {
var err error
udpListener, err = net.ListenPacket("udp4", ":3457")
Expect(err).ToNot(HaveOccurred())
go listenForEvents(origin)
dropsonde.Initialize("localhost:3457", origin...)
sender := metric_sender.NewMetricSender(dropsonde.AutowiredEmitter())
batcher := metricbatcher.New(sender, 100*time.Millisecond)
metrics.Initialize(sender, batcher)
})
AfterEach(func() {
udpListener.Close()
})
It("emits HTTP client/server events", func() {
httpListener, err := net.Listen("tcp", "localhost:0")
Expect(err).ToNot(HaveOccurred())
defer httpListener.Close()
httpHandler := dropsonde.InstrumentedHandler(FakeHandler{})
go http.Serve(httpListener, httpHandler)
_, err = http.Get("http://" + httpListener.Addr().String())
Expect(err).ToNot(HaveOccurred())
metrics.SendValue("TestMetric", 0, "")
metrics.IncrementCounter("TestIncrementCounter")
metrics.BatchIncrementCounter("TestBatchedCounter")
示例9:
BeforeEach(func() {
testDoppler, _ = net.ListenPacket("udp", "localhost:3457")
node := storeadapter.StoreNode{
Key: "/healthstatus/doppler/z1/0",
Value: []byte("localhost"),
}
adapter := etcdRunner.Adapter()
adapter.Create(node)
adapter.Disconnect()
})
AfterEach(func() {
testDoppler.Close()
})
It("forwards hmac signed messages to a healthy doppler server", func(done Done) {
type signedMessage struct {
signature []byte
message []byte
}
defer close(done)
originalMessage := basicValueMessage()
expectedEnvelope := addDefaultTags(basicValueMessageEnvelope())
expectedMessage, _ := proto.Marshal(expectedEnvelope)
mac := hmac.New(sha256.New, []byte("shared_secret"))
示例10:
BeforeEach(func() {
fakeDoppler = eventuallyListensForUDP("localhost:3457")
node := storeadapter.StoreNode{
Key: "/healthstatus/doppler/z1/doppler_z1/0",
Value: []byte("localhost"),
}
adapter := etcdRunner.Adapter()
adapter.Create(node)
adapter.Disconnect()
time.Sleep(200 * time.Millisecond) // FIXME: wait for metron to discover the fake doppler ... better ideas welcome
})
AfterEach(func() {
fakeDoppler.Close()
})
Context("with a fake statsd client", func() {
It("outputs gauges as signed value metric messages", func(done Done) {
connection, err := net.Dial("udp", "localhost:51162")
Expect(err).ToNot(HaveOccurred())
defer connection.Close()
statsdmsg := []byte("fake-origin.test.gauge:23|g\nfake-origin.sampled.gauge:23|g|@0.2")
_, err = connection.Write(statsdmsg)
Expect(err).ToNot(HaveOccurred())
expected := basicValueMetric("test.gauge", 23, "gauge")
Eventually(getValueMetric).Should(Equal(expected))
示例11:
BeforeEach(func() {
var err error
logMessages = nil
udpConn, err = net.ListenPacket("udp4", ":0")
Expect(err).ToNot(HaveOccurred())
go listenForLogs()
udpAddr := udpConn.LocalAddr().(*net.UDPAddr)
dropsonde.Initialize(fmt.Sprintf("localhost:%d", udpAddr.Port), origin...)
sender := metric_sender.NewMetricSender(dropsonde.AutowiredEmitter())
batcher := metricbatcher.New(sender, 100*time.Millisecond)
metrics.Initialize(sender, batcher)
})
AfterEach(func() {
udpConn.Close()
})
It("sends dropped error message for messages which are just under 64k and don't fit in UDP packet", func() {
logSender := log_sender.NewLogSender(dropsonde.AutowiredEmitter(), time.Second, loggertesthelper.Logger())
const length = 64*1024 - 1
reader := strings.NewReader(strings.Repeat("s", length) + "\n")
logSender.ScanErrorLogStream("someId", "app", "0", reader)
Eventually(func() []*events.LogMessage {
logLock.RLock()
defer logLock.RUnlock()
return logMessages
}).Should(HaveLen(1))
示例12:
EncryptionKeys: []string{"label:key"},
ActiveKeyLabel: "label",
ConvergeRepeatInterval: time.Hour,
}
storeClient = etcd.NewStoreClient(etcdClient)
consulHelper = test_helpers.NewConsulHelper(logger, consulClient)
})
var _ = AfterEach(func() {
ginkgomon.Kill(bbsProcess)
// Make sure the healthcheck server is really gone before trying to start up
// the bbs again in another test.
Eventually(func() error {
conn, err := net.Dial("tcp", bbsHealthAddress)
if err == nil {
conn.Close()
return nil
}
return err
}).Should(HaveOccurred())
auctioneerServer.Close()
testMetricsListener.Close()
Eventually(testMetricsChan).Should(BeClosed())
sqlRunner.Reset()
})
示例13: processLoop
// receives packets from the receive loop and dispatches them
// to their corresponding connections
func processLoop(c net.PacketConn, l *listener, rld *receiveLoopData, pld *processLoopData) {
var (
quit bool
wg = new(sync.WaitGroup)
tq = newTimerQueue()
connections = struct {
sync.RWMutex
M map[uint32]*connection
}{
M: make(map[uint32]*connection),
}
)
// keep a refcount to `c` for ourselves
wg.Add(1)
defer wg.Done()
// wait for all pending connections, then close the socket
go func() {
wg.Wait()
c.Close()
tq.Close()
}()
// generate a new key for cookies
cookieKey := make([]byte, sha1.Size)
if _, err := crand.Read(cookieKey); err != nil {
l.L.Lock()
l.err = fmt.Errorf("Failed to generate cookie secret: %v", err)
l.L.Unlock()
l.Broadcast()
return
}
sig := hmac.New(sha1.New, cookieKey)
// generate addler32(localaddr)
var localAddrSum [4]byte
binary.LittleEndian.PutUint32(localAddrSum[:], adler32.Checksum([]byte(c.LocalAddr().String())))
shouldWait := func() bool {
waitOnConnections := pld.rejectNewConnections && pld.remainingConnections == 0
return pld.err == nil && len(pld.Q) == 0 && !waitOnConnections
}
var packets []processLoopPacket
for !quit {
// wait for a packet to become available
pld.L.Lock()
for shouldWait() {
pld.Wait()
}
rejectNewConnections := pld.rejectNewConnections
pldErr := pld.err
quit = pldErr != nil
packets, pld.Q = pld.Q, packets[:0]
remainingConnections := pld.remainingConnections
pld.L.Unlock()
if rejectNewConnections && remainingConnections == 0 {
quit = true
}
// process packets
for ii := range packets {
buffer, addr := packets[ii].D, packets[ii].A
switch PacketType(buffer[0]) {
case PacketInit:
// are we accepting new connections?
if rejectNewConnections {
continue
}
// verify length
const MinInitPacketLength = 9
if len(buffer) < MinInitPacketLength {
continue
}
// verify protocol magic
if !bytes.Equal(buffer[1:5], protocolMagic) {
continue
}
// verify version
if buffer[5] != version1 {
sendAbort(c, addr, buffer[6:9])
continue
}
var outgoing [32]byte
now := time.Now()
outgoing[0] = byte(PacketCookie)
if _, err := crand.Read(outgoing[1:4]); err != nil {
return
//.........这里部分代码省略.........
示例14: TestExperiment
package experiment_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"net"
"testing"
)
func TestExperiment(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Experiment Suite")
}
var fakeMetron net.PacketConn
var _ = BeforeSuite(func() {
var err error
fakeMetron, err = net.ListenPacket("udp4", ":51161")
if err != nil {
panic(err)
}
})
var _ = AfterSuite(func() {
fakeMetron.Close()
})
示例15: serveUDP
func serveUDP(conf *Config, localHWAddr tap.HwAddr) error {
cipher, err := ss.NewCipher(conf.User.Method, conf.User.Password)
if err != nil {
return err
}
test := net.ParseIP(conf.Server.Ip)
v6 := false
if test.To4() == nil {
v6 = true
}
var addr string
if v6 {
addr = fmt.Sprintf("[%s]:%d", conf.Server.Ip, conf.Server.Port)
} else {
addr = fmt.Sprintf("%s:%d", conf.Server.Ip, conf.Server.Port)
}
ln, err := net.ListenPacket("udp", addr)
if err != nil {
return err
}
var listener net.PacketConn
if *enc {
listener = ln
} else {
listener = ss.NewPacketConn(ln, cipher.Copy())
}
defer listener.Close()
log.Printf("Server inited, listen on : %s:%d.\n", conf.Server.Ip, conf.Server.Port)
for {
buf := make([]byte, MaxPacketSize)
n, addr, err := listener.ReadFrom(buf)
if err != nil {
log.Println("[server]: Failed to read:", err)
}
if v, ok := hub.Packet_clients[addr]; !ok {
auth := new(Auth)
var mac tap.HwAddr
err = auth.Unmarshal(buf[:n])
if err != nil {
log.Println("[Read]: Failed to Unmarshal data:", err)
}
if auth.Type != Auth_Hello {
log.Println("[Read]: Unexpected message type.")
}
copy(mac[:], auth.MacAddr[:6])
response := new(Auth)
response.Type = Auth_Welcome
response.IP = "192.168.1.101/24"
response.DNS = "8.8.8.8"
response.MTU = int32(1500)
response.GateWay = "192.168.1.1"
response.MacAddr = localHWAddr[:]
data, err := response.Marshal()
if err != nil {
log.Println("Faield to encode config:", err)
}
client := &Client{MacAddr: mac, PacketConn: listener, is_packet: true, input: make(chan []byte, 8), remoteAddr: addr}
client.Write(data)
hub.Connect(client)
} else {
v.input <- buf[:n]
}
}
}