示例#1
0
func initSockets(BROADCAST_IP string, PORTNUM_COST string, PORTNUM_ORDER string) bool {

	//Create broadcast socket for orders
	broadcast_udp_addr, err := net.ResolveUDPAddr("udp", BROADCAST_IP+PORTNUM_ORDER)
	if err != nil {
		log.Println(" ResolveUDPAddr failed", err)
	}

	broadcast_order_conn, err := net.DialUDP("udp", nil, broadcast_udp_addr)
	if err != nil {
		log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err)
		return false
	}
	broadcast_order_conn = broadcast_order_conn

	//Create broadcast socket for cost updates
	broadcast_udp_addr, err = net.ResolveUDPAddr("udp", BROADCAST_IP+PORTNUM_COST)
	if err != nil {
		log.Println("ResolveUDPAddr failed", err)
	}

	broadcast_cost_conn, err = net.DialUDP("udp", nil, broadcast_udp_addr)
	if err != nil {
		log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err)
		return false
	}
	broadcast_cost_conn = broadcast_cost_conn

	//Create receiver socket for external orders
	listen_addr, err := net.ResolveUDPAddr("udp", PORTNUM_ORDER)
	if err != nil {
		log.Println("ResolveUDPAddr failed ", err)
	}

	receive_order_conn, err := net.ListenUDP("udp", listen_addr)
	if err != nil {
		log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err)
		return false
	}
	receive_order_conn = receive_order_conn

	//Create receiver socket for cost updates
	listen_addr, err = net.ResolveUDPAddr("udp", PORTNUM_COST)
	if err != nil {
		log.Println("ResolveUDPAddr failed ", err)
	}

	receive_cost_conn, err := net.ListenUDP("udp", listen_addr)
	if err != nil {
		log.Println("Could not establish UDP connection. Enter single eleveator mode.\n", err)
		return false
	}
	receive_cost_conn = receive_cost_conn

	return true
}
示例#2
0
文件: all_test.go 项目: cznic/dns
func TestExchange3(t *testing.T) {
	m := &Message{}
	m.Header.ID = GenID()
	m.Question.STAR("google.com", rr.CLASS_IN)
	m.RD = true
	m2 := &Message{}
	m2.Header.ID = GenID()
	m2.Question.STAR("google.cz", rr.CLASS_IN)
	m2.RD = true
	addr, err := net.ResolveUDPAddr("udp", "8.8.8.8:53")
	if err != nil {
		t.Fatal(err)
	}

	c, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		t.Fatal(err)
	}

	defer c.Close()
	addr, err = net.ResolveUDPAddr("udp", "8.8.4.4:53")
	if err != nil {
		t.Error(err)
		return
	}

	c.SetDeadline(time.Now().Add(5 * time.Second))
	c2, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		t.Error(err)
		return
	}

	defer c2.Close()
	c2.SetDeadline(time.Now().Add(5 * time.Second))
	ch := m.GoExchange(c, 2000, m2.GoExchange(c2, 2000, nil))

	re := <-ch
	if re.error != nil {
		t.Error(re.error)
		return
	}

	t.Log(re.Message)

	re = <-ch
	if re.error != nil {
		t.Error(40, re.error)
		return
	}

	t.Log(re.Message)
}
示例#3
0
func ServeServerList(rw http.ResponseWriter, req *http.Request) {
	addr, _ := net.ResolveUDPAddr("udp", "hl2master.steampowered.com:27011")
	conn, _ := net.DialUDP("udp", nil, addr)
	defer conn.Close()
	conn.Write([]byte("\x31\xFF0.0.0.0:0\x00\\appid\\225600\\gamedir\\berimbau\\empty\\1\x00"))

	buf := make([]byte, 512)
	conn.SetReadDeadline(time.Now().Add(5 * time.Second))
	readBytes, err := conn.Read(buf)
	if err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		return
	}
	var srvs []Server
	i := 6
	for i+6 < readBytes {
		srv := Server{}
		srv.Address = net.IPv4(buf[i], buf[i+1], buf[i+2], buf[i+3])
		srv.Port = uint16(buf[i+4])<<8 + uint16(buf[i+5])

		addr, _ = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", srv.Address.String(), srv.Port))
		conn, _ = net.DialUDP("udp", nil, addr)
		defer conn.Close()
		conn.Write([]byte("\xFF\xFF\xFF\xFF\x54Source Engine Query\x00"))

		srvbuf := make([]byte, 512)
		conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
		srvReadBytes, err := conn.Read(srvbuf)
		_ = srvReadBytes
		if err != nil {
			log.Println(err)
			i += 6
			continue
		}
		curIndex := 6
		srv.Name = getString(srvbuf, curIndex)
		curIndex += len(srv.Name) + 1
		srv.Map = getString(srvbuf, curIndex)
		curIndex += len(srv.Map) + 1
		curIndex += len(getString(srvbuf, curIndex)) + 1 //skip folder
		curIndex += len(getString(srvbuf, curIndex)) + 1 //skip game
		curIndex += 2                                    //skip gameid
		srv.PlayerCount = srvbuf[curIndex]
		srv.Capacity = srvbuf[curIndex+1]
		srvs = append(srvs, srv)
		i += 6
	}
	sort.Sort(Servers(srvs))
	rw.Header().Add("content-type", "text/html; charset=utf-8")
	tpl.Execute(rw, srvs)
	return
}
示例#4
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Println("Version: 1.0")

	var passer msgpasser.Passer
	passer.Init(9999)
	time.Sleep(3 * time.Second)

	for i, addrS := range addrs {
		addr, _ := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:9999", addrS))
		conn, _ := net.DialUDP("udp", nil, addr)
		data := msgpasser.GameRoomData{"game room info", 0, nil, len(names), names[i], "join", localName}
		data.Players = make([]msgpasser.PlayerInfo, len(names))
		for i := range names {
			data.Players[i].Ip = addrs[i]
			data.Players[i].Name = names[i]
		}
		b, err := json.Marshal(&data)
		log.Println(string(b))
		if err != nil {
			log.Println(err)
		}
		_, err = conn.Write(b)
		if err != nil {
			log.Println(err)
		}
	}

	addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:9999")
	conn, _ := net.DialUDP("udp", nil, addr)

	// To avoid too many input happen
	time.Sleep(3 * time.Second)

	x := 10000
	y := 3
	for i := 0; i < x; i++ {
		for j := 0; j < y; j++ {
			msg := msgpasser.Data{fmt.Sprintf("%v %d", localName, i*y+j), true}
			b, _ := json.Marshal(&msg)
			conn.Write(b)
		}
		time.Sleep(300 * time.Millisecond)
	}

	for {
		time.Sleep(30 * time.Second)
		log.Println("I am still alive!")
	}
}
示例#5
0
func main() {
	var statsdHost = flag.String("statsd_host", "127.0.0.1", "Statsd host")
	var statsdPort = flag.Int("statsd_port", 8125, "Statsd host")
	var nodename = flag.String("nodename", "riak", "Riak node name")
	var riakHost = flag.String("riak_host", "127.0.0.1", "Riak host")
	var riakHttpPort = flag.Int("riak_http_port", 8098, "Riak HTTP port")
	flag.Parse()

	// First ping to node to make sure it works
	err := pingRiak(*riakHost, *riakHttpPort)
	if err != nil {
		log.Fatalf("Error: %v", err)
		os.Exit(1)
	}
	statsd := fmt.Sprintf("%s:%d", *statsdHost, *statsdPort)
	addr, err := net.ResolveUDPAddr("udp", statsd)
	if err != nil {
		log.Fatalf("Couldn't resolve UDP addr: %v", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalf("Couldn't connect to statsd at %s", statsd)
		os.Exit(1)
	}

	// every 60s run hit the stats endpoint and then send to statsd
	interval := time.NewTicker(time.Second * 60)
	for _ = range interval.C {
		go getAndSendRiakMetrics(conn, *nodename, *riakHost, *riakHttpPort)
	}
}
示例#6
0
文件: main.go 项目: cyfdecyf/iidr
func doProxyClientDNS(reqData []byte, client *net.UDPAddr) []byte {
	conn, err := net.DialUDP("udp", nil, server)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Can't dial server: %v\n", err)
		os.Exit(1)
	}
	defer conn.Close()
	_, err = conn.Write(reqData)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to write to server: %v\n", err)
		return nil
	}
	t := time.Now().Add(time.Duration(5) * time.Second)
	conn.SetReadDeadline(t)
	var rep []byte
	for {
		repData := make([]byte, 2048)
		nr, err := conn.Read(repData)
		if err != nil {
			err2, ok := err.(*net.OpError)
			if ok && err2.Timeout() {
				break
			}
			fmt.Fprintf(os.Stderr, "Failed to read from server: %v\n", err)
			break
		}
		rep = repData[:nr]
	}
	return rep
}
示例#7
0
func sendImAlive() {
	service := broadcast + ":" + UDPport
	addr, err := net.ResolveUDPAddr("udp4", service)
	if err != nil {
		fmt.Println("net.ResolveUDPAddr error in sendImAlive: ", err)
		internal.setupFail <- true
	}

	isalivesocket, err := net.DialUDP("udp4", nil, addr)
	if err != nil {
		fmt.Println("net.DialUDP error in sendImAlive: ", err)
		internal.setupFail <- true
	}
	isAliveMessage := []byte("ping")

	for {
		select {
		case <-internal.quitsendImAlive:
			return
		default:
			_, err := isalivesocket.Write(isAliveMessage)
			if err != nil {
				fmt.Println("Write error in sendImAlive: ", err)
			}
			time.Sleep(sleepduration * time.Millisecond)
		}
	}
}
示例#8
0
func SendMagicPacket(macAddr string, bcastAddr string, bcastPort string) error {

	if len(macAddr) != (6*2 + 5) {
		return errors.New("Invalid MAC Address String: " + macAddr)
	}

	packet, err := constructMagicPacket(macAddr)
	if err != nil {
		return err
	}

	a, err := net.ResolveUDPAddr("udp", bcastAddr+":"+bcastPort)
	if err != nil {
		return err
	}

	c, err := net.DialUDP("udp", nil, a)
	if err != nil {
		return err
	}

	written, err := c.Write(packet)
	c.Close()

	// Packet must be 102 bytes in length
	if written != 102 {
		return err
	}

	return nil
}
示例#9
0
func Dial(dest v2net.Destination) (net.Conn, error) {
	var ip net.IP
	if dest.Address().IsIPv4() || dest.Address().IsIPv6() {
		ip = dest.Address().IP()
	} else {
		ips, err := net.LookupIP(dest.Address().Domain())
		if err != nil {
			return nil, err
		}
		if len(ips) == 0 {
			return nil, ErrInvalidHost
		}
		ip = ips[dice.Roll(len(ips))]
	}
	if dest.IsTCP() {
		return net.DialTCP("tcp", nil, &net.TCPAddr{
			IP:   ip,
			Port: int(dest.Port()),
		})
	} else {
		return net.DialUDP("udp", nil, &net.UDPAddr{
			IP:   ip,
			Port: int(dest.Port()),
		})
	}
}
示例#10
0
func udp_init() (err error) {
	//Generating broadcast address
	baddr, err = net.ResolveUDPAddr("udp4", "255.255.255.255:"+strconv.Itoa(30000))
	if err != nil {
		return err
	}

	//Generating localaddress
	tempConn, err := net.DialUDP("udp4", nil, baddr)
	defer tempConn.Close()
	tempAddr := tempConn.LocalAddr()
	laddr, err = net.ResolveUDPAddr("udp4", tempAddr.String())
	laddr.Port = 30000 //localListenPort

	//Creating local listening connections
	//localListenConn, err := net.ListenUDP("udp4", laddr)
	//if err != nil {
	//	return err
	//	}

	//Creating listener on broadcast connection
	//broadcastListenConn, err := net.ListenUDP("udp", baddr)
	//if err != nil {
	//	localListenConn.Close()
	//	return err
	//}

	//go udp_receive_server(localListenConn, broadcastListenConn, 1024, receive_ch)
	//go udp_transmit_server(localListenConn, broadcastListenConn, send_ch)

	fmt.Printf("Generating local address: \t Network(): %s \t String(): %s \n", laddr.Network(), laddr.String())
	fmt.Printf("Generating broadcast address: \t Network(): %s \t String(): %s \n", baddr.Network(), baddr.String())
	return err
}
示例#11
0
func (logstash *Logstash) sender() {
	for {
		ServerAddress, err := net.ResolveUDPAddr("udp", logstash.Address)
		if err != nil {
			logger.Error("Can't resolve remote UDP address: %s", err.Error())
		} else {
			Conn, err := net.DialUDP("udp", nil, ServerAddress)
			if err != nil {
				logger.Error("Can't dial up: %s", err.Error())
			} else {
				logger.Notice("Connected to remote UDP address: %s", ServerAddress.String())
				for {
					select {
					case message := <-logstash.channel:
						if *debug {
							logger.Debug(fmt.Sprintf("Writing to UDP socket: %s", message))
						}
						_, err := Conn.Write([]byte(message))
						if err != nil {
							logger.Error("Can't write: %s", err.Error())
							Conn.Close()
							goto RETRY
						}
					}
				}

			}
		}

	RETRY:

		time.Sleep(retryTimeout)
	}
}
示例#12
0
// Udp client which sends a fixed num of packets to given port after a fixed delay.
// Delay ensures that capture code is ready to recv packets.
func udpClient(port int, numPkts int, wait time.Duration, t *testing.T) {
	time.Sleep(wait)

	addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", port))
	if err != nil {
		t.Logf("ERROR Failed to resolve udp addr err:%s", err)
		return
	}

	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		t.Logf("ERROR Failed to dial udp port:%d err:%s", port, err)
		return
	}

	t.Logf("Start packets to port:%d", port)

	pkt := []byte("hello")
	for i := 0; i < numPkts; i++ {
		if l, err := conn.Write(pkt); err != nil || l != len(pkt) {
			t.Logf("ERROR Failed to send packet size:%d wlen:%d err:%s", len(pkt), l, err)
		}
	}

	t.Logf("Completed sending packets to port:%d", port)
}
示例#13
0
文件: udp.go 项目: antongulenko/RTP
func NewUdpProxy(listenAddr, targetAddr string) (*UdpProxy, error) {
	var listenUDP, targetUDP *net.UDPAddr
	var err error
	if listenUDP, err = net.ResolveUDPAddr("udp", listenAddr); err != nil {
		return nil, err
	}
	if targetUDP, err = net.ResolveUDPAddr("udp", targetAddr); err != nil {
		return nil, err
	}

	listenConn, err := net.ListenUDP("udp", listenUDP)
	if err != nil {
		return nil, err
	}
	// TODO http://play.golang.org/p/ygGFr9oLpW
	// for per-UDP-packet addressing in case one proxy handles multiple connections
	targetConn, err := net.DialUDP("udp", nil, targetUDP)
	if err != nil {
		listenConn.Close()
		return nil, err
	}

	return &UdpProxy{
		listenConn:      listenConn,
		listenAddr:      listenUDP,
		targetConn:      targetConn,
		targetAddr:      targetUDP,
		packets:         make(chan []byte, BufferedPackets),
		proxyClosed:     golib.NewOneshotCondition(),
		writeErrors:     make(chan error, buf_write_errors),
		Stats:           stats.NewStats("UDP Proxy " + listenAddr),
		OnError:         OnErrorClose,
		writePausedCond: sync.Cond{L: new(sync.Mutex)},
	}, nil
}
示例#14
0
文件: all_test.go 项目: cznic/dns
func TestExchange2(t *testing.T) {
	m := &Message{}
	m.Header.ID = GenID()
	m.Question.NS("google.com", rr.CLASS_IN)
	ch := make(ExchangeChan, 10)
	addr, err := net.ResolveUDPAddr("udp", "8.8.8.8:53")
	if err != nil {
		t.Fatal(err)
	}

	c, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		t.Fatal(10, err)
	}

	defer c.Close()

	c.SetDeadline(time.Now().Add(5 * time.Second))
	re := <-m.GoExchange(c, 2000, ch)
	if re.error != nil {
		t.Fatal(20, re.error)
	}

	t.Log(re.Message)
}
示例#15
0
文件: all_test.go 项目: cznic/dns
func TestExchange1(t *testing.T) {
	m := &Message{}
	m.Header.ID = GenID()
	m.Question.A("localhost", rr.CLASS_IN)
	ch := make(ExchangeChan, 10)
	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:7")
	if err != nil {
		t.Fatal(err)
	}

	c, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		t.Fatal(10, err)
	}

	defer c.Close()

	c.SetDeadline(time.Now().Add(time.Millisecond))
	re := <-m.GoExchange(c, 2000, ch)
	if re.error == nil {
		t.Fatal(20)
	}

	t.Log(20, re.error)
}
示例#16
0
func NewStatterWithConfig(config *RouteConfig) Statter {
	logger := NewLogger("stats.%s", config.Name)
	hostname, _ := os.Hostname()
	hostIp := os.Getenv("HOST_IP")
	if hostIp == "" {
		hostIp = "localhost"
	}

	addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:8125", hostIp))
	if err != nil {
		logger.Error("Unable to resolve UDP address: %v", err)
		return nil
	}

	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		logger.Error("Unable to create UDP connection: %v", err)
		return nil
	}

	return &statsdStatter{
		conn:     conn,
		addr:     addr,
		Name:     config.Name,
		Hostname: hostname,
		Logger:   logger,
	}
}
示例#17
0
func (c *Client) pingUdp() {

	var pingtime = 1 * time.Second

	localAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:0", c.localAddr))
	if err != nil {
		panic(err)
	}
	daemonAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", c.daemonAddr, c.daemonPortUdp))

	if err != nil {
		panic(err)
	}
	c.logger.Println("starting to pindg address", daemonAddr)
	con, err := net.DialUDP("udp", localAddr, daemonAddr)
	if err != nil {
		panic(err)
	}
	t := time.NewTimer(pingtime)
	s := c.stop.Future().AsChan()

	for {
		select {
		case <-s:
			return

		case <-t.C:
			con.Write([]byte(fmt.Sprintf("%s:%d", c.uuid, c.localPort)))
			t.Reset(pingtime)
		}
	}

}
示例#18
0
func TestDokodemoUDP(t *testing.T) {
	assert := unit.Assert(t)

	port := v2nettesting.PickPort()

	data2Send := "Data to be sent to remote."

	udpServer := &udp.Server{
		Port: port,
		MsgProcessor: func(data []byte) []byte {
			buffer := make([]byte, 0, 2048)
			buffer = append(buffer, []byte("Processed: ")...)
			buffer = append(buffer, data...)
			return buffer
		},
	}
	_, err := udpServer.Start()
	assert.Error(err).IsNil()

	pointPort := v2nettesting.PickPort()
	networkList := v2netjson.NetworkList([]string{"udp"})
	config := mocks.Config{
		PortValue: pointPort,
		InboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "dokodemo-door",
			SettingsValue: &json.DokodemoConfig{
				Host:    "127.0.0.1",
				Port:    int(port),
				Network: &networkList,
				Timeout: 0,
			},
		},
		OutboundConfigValue: &mocks.ConnectionConfig{
			ProtocolValue: "freedom",
			SettingsValue: nil,
		},
	}

	point, err := point.NewPoint(&config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	udpClient, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(pointPort),
		Zone: "",
	})
	assert.Error(err).IsNil()

	udpClient.Write([]byte(data2Send))

	response := make([]byte, 1024)
	nBytes, err := udpClient.Read(response)
	assert.Error(err).IsNil()
	udpClient.Close()

	assert.String("Processed: " + data2Send).Equals(string(response[:nBytes]))
}
示例#19
0
func TestUdpServe(t *testing.T) {
	key := make([]byte, 32)
	copy(key, "this is my key value!")

	udpaddr, err := net.ResolveUDPAddr("udp", "localhost:8080")
	if err != nil {
		t.Fatalf("ResolveUDPAddr error : %v\n", err)
	}

	udpconn, err := net.DialUDP("udp", nil, udpaddr)
	if err != nil {
		t.Fatalf("DialUDP error : %v\n", err)
	}
	defer udpconn.Close()
	udpconn.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))

	plaintext := []byte("a")
	ciphertext, err := server.EncryptData(key, plaintext, nil)
	if err != nil {
		t.Fatalf("EncryptData error : %v\n", err)
	}

	_, err = udpconn.Write(ciphertext)
	if err != nil {
		t.Fatalf("Write error : %v\n", err)
	}
}
示例#20
0
func (dhtNode *DHTNode) Send(msgId, req, dst, origin, key, data string) {
	// If the origin is empty, then it becomes the DHTNodes bind adress since it was the one who sent the first.
	/*if req == "LookupResponse" {
		fmt.Println("dst: " + dst + ", origin: " + origin + ", key: " + key + ", data: " + data)
	}*/
	if key == "" {
		key = dhtNode.nodeId
	}
	if origin == "" {
		origin = dhtNode.BindAddress
	}
	msg := CreateMsg(req, dhtNode.BindAddress, origin, key, data)
	if msgId != "" {
		msg.MsgId = msgId
	}

	udpAddr, err := net.ResolveUDPAddr("udp", dst)
	conn, err := net.DialUDP("udp", nil, udpAddr)
	defer conn.Close()
	if err != nil {
		fmt.Println(err.Error())
	}
	res, _ := json.Marshal(msg)
	_, err = conn.Write(res) // wat?
}
func main() {
	addr, err := net.ResolveUDPAddr("0.0.0.0:10000")
	if err != nil {
		handle_err(err)
	}

	addr_out, err := net.ResolveUDPAddr("localhost:10020")
	if err != nil {
		handle_err(err)
	}

	c, err := net.ListenUDP("udp4", addr)
	if err != nil {
		handle_err(err)
	}

	c_out, err := net.DialUDP("udp4", nil, addr_out)
	if err != nil {
		handle_err(err)
	}

	buf := make([]byte, 2000)
	for {
		length, _, err := c.ReadFrom(buf)
		if err != nil {
			handle_err(err)
		}
		c_out.Write(buf[0:length])
	}
}
示例#22
0
func (s *ServerSuite) TestTailFile(c *C) {
	handler := new(HandlerMock)
	server := NewServer()
	server.SetFormat(RFC3164)
	server.SetHandler(handler)
	server.ListenUDP("0.0.0.0:5141")
	server.ListenTCP("0.0.0.0:5141")

	go func(server *Server) {
		time.Sleep(100 * time.Millisecond)

		serverAddr, _ := net.ResolveUDPAddr("udp", "localhost:5141")
		con, _ := net.DialUDP("udp", nil, serverAddr)
		con.Write([]byte(exampleSyslog))
		time.Sleep(100 * time.Millisecond)

		server.Kill()
	}(server)

	server.Boot()
	server.Wait()

	c.Check(handler.LastLogParts["hostname"], Equals, "hostname")
	c.Check(handler.LastLogParts["tag"], Equals, "tag")
	c.Check(handler.LastLogParts["content"], Equals, "content")
	c.Check(handler.LastMessageLength, Equals, int64(len(exampleSyslog)))
	c.Check(handler.LastError, IsNil)
}
示例#23
0
文件: udp.go 项目: nulijiabei/socket
// 进行连接
func (udp *UDP) connect() error {
	// 创建地址结构
	addr, err := net.ResolveUDPAddr("udp", udp.addr+":"+udp.port)
	if err != nil {
		// 返回错误
		return err
	}
	// 计数器
	var i int = 0
	// 在有效次数内创建连接
	for {
		// 建立TCP连接
		conn, connErr := net.DialUDP("udp", nil, addr)
		if connErr == nil && conn != nil {
			// 设置缓冲区
			conn.SetReadBuffer(1048576)
			conn.SetWriteBuffer(1048576)
			// 将连接保存到对象
			udp.conn = conn
			// 跳出循环,连接成功
			break
		}
		// 判断计数器次数是否达到峰值
		if i > udp.maxRetry {
			return connErr
		}
		// 计数器计数
		i += 1
	}
	// 返回
	return nil
}
示例#24
0
// Accepts a UdpAction and a one-way channel to write the results to.
func DoUdpRequest(udpAction UdpAction, resultsChannel chan HttpReqResult, sessionMap map[string]string) {

	address := SubstParams(sessionMap, udpAction.Address)
	payload := SubstParams(sessionMap, udpAction.Payload)

	if udpconn == nil {
		ServerAddr, err := net.ResolveUDPAddr("udp", address) //"127.0.0.1:10001")
		if err != nil {
			fmt.Println("Error ResolveUDPAddr remote: " + err.Error())
		}

		LocalAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
		if err != nil {
			fmt.Println("Error ResolveUDPAddr local: " + err.Error())
		}

		udpconn, err = net.DialUDP("udp", LocalAddr, ServerAddr)
		if err != nil {
			fmt.Println("Error Dial: " + err.Error())
		}
	}
	//defer Conn.Close()
	start := time.Now()
	if udpconn != nil {
		_, err = fmt.Fprintf(udpconn, payload+"\r\n")
	}
	if err != nil {
		fmt.Printf("UDP request failed with error: %s\n", err)
		udpconn = nil
	}

	elapsed := time.Since(start)
	resultsChannel <- buildUdpResult(0, 200, elapsed.Nanoseconds(), udpAction.Title)

}
示例#25
0
func main() {

	udpAddr, err := net.ResolveUDPAddr("udp", ":20014")
	if err != nil {
		log.Fatal(err)
	}

	udpListen, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		log.Fatal(err)
	}

	backupvalue := backup(udpListen)
	fmt.Println(backupvalue)

	udpListen.Close()

	udpAddr, err = net.ResolveUDPAddr("udp", "129.241.187.255:20014")
	if err != nil {
		log.Fatal(err)
	}

	udpBroadcast, err := net.DialUDP("udp", nil, udpAddr)
	if err != nil {
		log.Fatal(err)
	}

	primary(backupvalue, udpBroadcast)

	udpBroadcast.Close()

}
示例#26
0
文件: udp.go 项目: eleneme/sanntid
func connect(ip string) (connection *net.UDPConn) {
	var address string
	if ip == "" {
		//Broadcast
		address = "129.241.187.255:" + PORT
	} else {
		address = ip + ":" + PORT
	}

	sendAddr, err := net.ResolveUDPAddr("udp", address)
	conn, err2 := net.DialUDP("udp", nil, sendAddr)

	if err != nil || err2 != nil {
		fmt.Println("Error connecting")
		return nil
	}

	if ip == "" {
		fmt.Println("Broadcast connection established")
		Broadcast.Conn = conn
	} else {
		fmt.Println("Connected to: ", ip)
		AppendConn(conn, ip)
	}

	return conn
}
示例#27
0
文件: main.go 项目: zhangbo7364/mlzel
func Main() {
	var serverAddr *net.UDPAddr
	var err error
	serverAddr, err = net.ResolveUDPAddr("udp4", "127.0.0.1:8888")
	if err != nil {
		log.Println("ip error!", err)
		return
	}
	log.Println("serverAddr", err)

	socket, err := net.DialUDP("udp4", nil, serverAddr)
	if err != nil {
		log.Println("connection error!", err)
		return
	}
	defer socket.Close()

	for {
		senddata := []byte("hello server!")
		_, err = socket.Write(senddata)
		if err != nil {
			fmt.Println("send data error", err)
			return
		}

		data := make([]byte, 4096)
		read, remoteAddr, err := socket.ReadFromUDP(data)
		if err != nil {
			fmt.Println("read data error", err)
			return
		}
		fmt.Println(read, remoteAddr)
		fmt.Printf("%s\n", data)
	}
}
示例#28
0
func main() {
	flag.Parse()

	ip := net.ParseIP(*address)
	socket, err := net.DialUDP("udp4", nil, &net.UDPAddr{
		IP:   ip,
		Port: *port,
	})
	if err != nil {
		panic(err.String())
	}
	defer socket.Close()

	for {
		label := randomLabels[rand.Intn(len(randomLabels))]
		var message string
		if rand.Intn(2) < 1 {
			message = `{"type":` + strconv.Itoa(appchilada.EventTypeCount) + `,"name":"` + label + `","value":` + strconv.Itoa(rand.Intn(5)+1) + `}`
		} else {
			message = `{"type":` + strconv.Itoa(appchilada.EventTypeTiming) + `,"name":"` + label + `","value":` + strconv.Itoa(rand.Intn(1000)+10) + `}`
		}
		println(message)
		if _, err := socket.Write([]byte(message)); err != nil {
			println(err.String())
			break
		}
		time.Sleep(int64(rand.Intn(10) * 1e7))
	}
}
示例#29
0
func query(msg []byte) ([]byte, error) {
	raddr, err := net.ResolveUDPAddr("udp", *dns)
	if err != nil {
		return nil, err
	}

	conn, err := net.DialUDP("udp", nil, raddr)
	defer conn.Close()

	if err != nil {
		return nil, err
	}

	_, err = conn.Write(msg)
	if err != nil {
		return nil, err
	}

	ret := make([]byte, 4096)
	n, _, err := conn.ReadFromUDP(ret)
	if err != nil {
		return nil, err
	}

	return ret[0:n], nil
}
示例#30
0
文件: peer.go 项目: subutai-io/p2p
// TestConnection method tests connection with specified endpoint
func (np *NetworkPeer) TestConnection(ptpc *PeerToPeer, endpoint *net.UDPAddr) bool {
	msg := CreateTestP2PMessage(ptpc.Crypter, "TEST", 0)
	conn, err := net.DialUDP("udp4", nil, endpoint)
	if err != nil {
		Log(Debug, "%v", err)
		return false
	}
	ser := msg.Serialize()
	_, err = conn.Write(ser)
	if err != nil {
		conn.Close()
		return false
	}
	t := time.Now()
	t = t.Add(3 * time.Second)
	conn.SetReadDeadline(t)
	// TODO: Check if it was real TEST message
	for {
		var buf [4096]byte
		s, _, err := conn.ReadFromUDP(buf[0:])
		if err != nil {
			Log(Debug, "%v", err)
			conn.Close()
			break
		}
		if s > 0 {
			conn.Close()
			return true
			break
		}
	}
	conn.Close()
	return false
}