예제 #1
0
파일: udp.go 프로젝트: frimkus/ttk4145-ex3
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
0
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
0
파일: udp.go 프로젝트: frimkus/ttk4145-ex3
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
0
/*
	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
0
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
0
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
0
파일: main.go 프로젝트: it-man-cn/go-acs
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
0
// 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
0
파일: NetInput.go 프로젝트: aktungmak/chq
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
0
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
0
파일: dht.go 프로젝트: subutai-io/p2p
// 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
0
파일: server.go 프로젝트: h2non/dns
// 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
0
파일: network.go 프로젝트: HaMster21/gnarly
// 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
0
파일: udp.go 프로젝트: Aarvold/Heismappe
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
0
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()
}
예제 #16
0
// serveUDP starts a UDP listener for the server.
// Each request is handled in a seperate goroutine.
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 {
		if srv.ReadTimeout != 0 {
			l.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
		}
		if srv.WriteTimeout != 0 {
			l.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
		}
		m := make([]byte, srv.UDPSize)
		n, a, e := l.ReadFromUDP(m)
		if e != nil || n == 0 {
			// don't bail out, but wait for a new request
			continue
		}
		m = m[:n]
		go serve(a, handler, m, l, nil, srv.TsigSecret)
	}
	panic("dns: not reached")
}
예제 #17
0
// serveUDP starts a UDP listener for the server.
// Each request is handled in a separate goroutine.
func (srv *Server) serveUDP(l *net.UDPConn) error {
	defer l.Close()

	if srv.NotifyStartedFunc != nil {
		srv.NotifyStartedFunc()
	}

	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	rtimeout := srv.getReadTimeout()
	// deadline is not used here
	for {
		m, s, e := srv.readUDP(l, rtimeout)
		select {
		case <-srv.stopUDP:
			return nil
		default:
		}
		if e != nil {
			continue
		}
		srv.wgUDP.Add(1)
		go srv.serve(s.RemoteAddr(), handler, m, l, s, nil)
	}
	panic("dns: not reached")
}
예제 #18
0
파일: server.go 프로젝트: thinkingo/wagl
// serveUDP starts a UDP listener for the server.
// Each request is handled in a separate goroutine.
func (srv *Server) serveUDP(l *net.UDPConn) error {
	defer l.Close()

	if srv.NotifyStartedFunc != nil {
		srv.NotifyStartedFunc()
	}

	reader := Reader(&defaultReader{srv})
	if srv.DecorateReader != nil {
		reader = srv.DecorateReader(reader)
	}

	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	rtimeout := srv.getReadTimeout()
	// deadline is not used here
	for {
		m, s, e := reader.ReadUDP(l, rtimeout)
		srv.lock.RLock()
		if !srv.started {
			srv.lock.RUnlock()
			return nil
		}
		srv.lock.RUnlock()
		if e != nil {
			continue
		}
		srv.inFlight.Add(1)
		go srv.serve(s.RemoteAddr(), handler, m, l, s, nil)
	}
}
예제 #19
0
파일: router.go 프로젝트: adieu/weave
func (router *Router) udpReader(conn *net.UDPConn, po PacketSink) {
	defer conn.Close()
	dec := NewEthernetDecoder()
	handleUDPPacket := router.handleUDPPacketFunc(dec, po)
	buf := make([]byte, MaxUDPPacketSize)
	for {
		n, sender, err := conn.ReadFromUDP(buf)
		if err == io.EOF {
			return
		} else if err != nil {
			log.Println("ignoring UDP read error", err)
			continue
		} else if n < NameSize {
			continue // TODO something different?
		} else {
			name := PeerNameFromBin(buf[:NameSize])
			packet := make([]byte, n-NameSize)
			copy(packet, buf[NameSize:n])
			udpPacket := &UDPPacket{
				Name:   name,
				Packet: packet,
				Sender: sender}
			peerConn, found := router.Ourself.ConnectionTo(name)
			if !found {
				continue
			}
			relayConn, ok := peerConn.(*LocalConnection)
			if !ok {
				continue
			}
			checkWarn(relayConn.Decryptor.IterateFrames(handleUDPPacket, udpPacket))
		}
	}
}
예제 #20
0
//TickServer 将 c 传入的数据广播到局域网
func (server *UDPServer) TickServer(c <-chan []byte) (err error) {
	var conn *net.UDPConn
	fmt.Println("start TickServer")
	server.slock.Lock()
	for i := 0; i < 3; i++ {
		conn, err = net.DialUDP("udp", server.sendAddr, server.bcastAddr)
		if err == nil {
			break
		} else {
			fmt.Println("DialUDP err:", err)
		}
		time.Sleep(3 * time.Millisecond)
	}

	defer func() {
		if err := recover(); err != nil {
			fmt.Println("MY:", err)
		}
	}()
	stop := false
	p := &packet.NoticePacket{packet.STATE_OFFLINE, []byte(""), []byte("")}
	buf, _ := json.Marshal(p) //make the init packet
	tickchan := make(chan []byte, 128)
	go func(c chan []byte) { //tick function
		defer func() {
			conn.Close()
			server.slock.Unlock()
			fmt.Println("stop udp TickServer FINISH.")
		}()
		for {
			if stop {
				return
			}
			//fmt.Println("send: ", string(buf))
			_, err = conn.Write(buf)
			errorCheck(err)
			time.Sleep(time.Duration(server.tick) * time.Millisecond)
		}
	}(tickchan)
	for {
		timeout := make(chan bool)
		go func() {
			time.Sleep(5000 * time.Millisecond)
			timeout <- true
		}()
		select {
		case buf = <-c:
			//tickchan <- buf
		case <-timeout: //超时检测
		case <-server.sexitchan: //退出
			//server.slock.Lock()
			fmt.Println("stop udp TickServer....")
			stop = true
			return nil
		}
	}

	return nil
}
예제 #21
0
파일: phoenix.go 프로젝트: eleneme/sanntid
func recieve(conn *net.UDPConn) {
	received := make([]byte, 1)
	for Master == 0 {
		_, _, _ = conn.ReadFromUDP(received)
		LastSignal = time.Now()
	}
	conn.Close()
}
예제 #22
0
func TerminateConn(conn net.UDPConn) int {
	err := conn.Close()
	if err != nil {
		fmt.Println("Error closing connection: (UDP)", err.Error())
		return -1
	} else {
		return 1
	}
}
예제 #23
0
파일: client.go 프로젝트: superboum/udptest
func udpTest(Conn *net.UDPConn) bool {
	buf := make([]byte, 1024)

	Conn.SetReadDeadline(time.Now().Add(1 * time.Second))
	Conn.Write([]byte("TEST"))
	n, _, _ := Conn.ReadFromUDP(buf)
	Conn.Close()
	return string(buf[:n]) == "OK\n"
}
예제 #24
0
파일: udp.go 프로젝트: eleneme/sanntid
func recieve(conn *net.UDPConn) {
	//Recieve message from network
	recieved := make([]byte, 500)
	for true {
		_, _, _ = conn.ReadFromUDP(recieved)
		go recieveMessage(string(recieved))
	}
	conn.Close()
}
예제 #25
0
func (this *SearchGateway) SendMessage() (result string, err error) {
	//Send broadcast messages to bring the port, formats such as: "239.255.255.250:1900"
	var conn *net.UDPConn
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic err: %s", r)
		}
	}()
	//go func(conn *net.UDPConn) {
	//	defer func() {
	//		if r := recover(); r != nil {
	//			log.Printf("panic in timeout conn err: %s", err)
	//		}
	//	}()
	//	//Timeout to 3 seconds
	//	time.Sleep(time.Second * 3)
	//	if err := conn.Close(); err != nil {
	//		log.Printf("conn close err: %s", err)
	//	}
	//}(conn)
	remotAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
	if err != nil {
		return "", fmt.Errorf("Multicast address format is incorrect err: %s", err)
	}

	locaAddr, err := net.ResolveUDPAddr("udp", this.upnp.LocalHost+":0")
	if err != nil {
		return "", fmt.Errorf("Local IP address is incorrent err: %s", err)
	}
	conn, err = net.ListenUDP("udp", locaAddr)
	if err != nil {
		return "", fmt.Errorf("Listening udp error err: %s", err)
	}
	defer func(conn net.Conn) {
		if err := conn.Close(); err != nil {
			log.Printf("conn close err: %s", err)
		}
	}(conn)

	_, err = conn.WriteToUDP([]byte(this.searchMessage), remotAddr)
	if err != nil {
		return "", fmt.Errorf("Sent to a multicast address err: %s", err)
	}

	buf := make([]byte, 1024)

	n, _, err := conn.ReadFromUDP(buf)
	if err != nil {
		return "", fmt.Errorf("Error message received from a multicast address")
	}

	return string(buf[:n]), nil
}
예제 #26
0
// 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)
	}
}
예제 #27
0
func clientHandler(target string, termMon *termmon.TermMonitor, f base.ClientFactory, conn *net.UDPConn, proxyURI *url.URL) {
	defer conn.Close()
	termMon.OnHandlerStart()
	defer termMon.OnHandlerFinish()

	fmt.Println("@@@ handling...")

	tracker := make(ConnTracker)

	name := f.Transport().Name()

	fmt.Println("Transport is", name)

	buf := make([]byte, 1024)

	// Receive UDP packets and forward them over transport connections forever
	for {
		n, addr, err := conn.ReadFromUDP(buf)
		fmt.Println("Received ", string(buf[0:n]), " from ", addr)

		if err != nil {
			fmt.Println("Error: ", err)
		}

		fmt.Println(tracker)

		if state, ok := tracker[addr.String()]; ok {
			// There is an open transport connection, or a connection attempt is in progress.

			if state.Waiting {
				// The connection attempt is in progress.
				// Drop the packet.
				fmt.Println("recv: waiting")
			} else {
				// There is an open transport connection.
				// Send the packet through the transport.
				fmt.Println("recv: write")
				fmt.Println("writing...")
				(*state.Conn).Write(buf)
			}
		} else {
			// There is not an open transport connection and a connection attempt is not in progress.
			// Open a transport connection.

			fmt.Println("Opening connection to ", target)

			openConnection(&tracker, addr.String(), target, termMon, f, proxyURI)

			// Drop the packet.
			fmt.Println("recv: Open")
		}
	}
}
예제 #28
0
파일: dht.go 프로젝트: subutai-io/p2p
// HandleStop - receives a stop command from DHT server. Stop means peer should be removed from environments
func (dht *DHTClient) HandleStop(data DHTMessage, conn *net.UDPConn) {
	if data.Arguments != "" {
		// We need to stop particular peer by changing it's state to
		// P_DISCONNECT
		Log(Info, "Stop command for %s", data.Arguments)
		if dht.RemovePeerChan == nil {
			dht.RemovePeerChan = make(chan string)
		}
		dht.RemovePeerChan <- data.Arguments
	} else {
		conn.Close()
	}
}
예제 #29
0
// 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.")
}
예제 #30
-1
func udpListener(conn *net.UDPConn, sendingFrom net.Addr, start *sync.WaitGroup, end *sync.WaitGroup) {
	fmt.Fprintln(os.Stderr, "Started listener...")
	start.Done()

	buff := make([]byte, 1600) // standard MTU size -- no packet should be bigger
	for i := 0; true; i++ {
		fmt.Fprintln(os.Stderr, "Waiting for packet #"+strconv.Itoa(i))
		len, from, err := conn.ReadFromUDP(buff)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error receiving UDP packet: "+err.Error())
		}
		if from.String() == sendingFrom.String() {
			i--
			continue
		}

		str := string(buff[:len])
		fmt.Println("Received message from " + from.String() + "\n\t" + str)
		if strings.Contains(str, "<<terminate>>") {
			conn.Close()
			fmt.Fprintln(os.Stderr, "Terminated UDP listener")
			end.Done()
			return
		}
	}
}