• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2018 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// TODO(jophba): Use proper testing framework
6
7package main
8
9import (
10	"bytes"
11	"context"
12	"io"
13	"fmt"
14	"log"
15
16	"osp"
17)
18
19func testMdns() {
20	// TODO(jophba): log error if it fails
21	ctx := context.Background()
22	instance := "TV"
23	port := 10000
24	go osp.RunMdnsServer(ctx, instance, port)
25	entries, err := osp.BrowseMdns(ctx)
26	if (err != nil) {
27		log.Fatalf("Failed to browse mDNS: %v\n", err)
28	}
29	for entry := range entries {
30		log.Println(fmt.Sprintf("%s at %s(%s or %s):%d", entry.Instance, entry.HostName, entry.AddrIPv4, entry.AddrIPv6, entry.Port))
31	}
32	log.Println("No more entries.")
33}
34
35func dialAndwriteQuicStream(ctx context.Context, hostname string, port int, msg []byte) {
36	clientSession, err := osp.DialAsQuicClient(ctx, hostname, port)
37	if err != nil {
38		log.Fatalln("Failed to dial QUIC:", err.Error())
39	}
40	clientStream, err := clientSession.OpenStreamSync()
41	if err != nil {
42		log.Fatalln("Failed to open QUIC stream:", err.Error())
43	}
44	_, err = clientStream.Write(msg)
45	if err != nil {
46		log.Fatalln("Failed to write to a QUIC stream:", err.Error())
47	}
48}
49
50func testQuic() {
51	const port = 4242
52	msg := []byte("Hello, World")
53	tlsCert, err := osp.GenerateTlsCert()
54	if err != nil {
55		log.Fatalln("Failed to generate TLS cert:", err.Error())
56	}
57
58	ctx, cancel := context.WithCancel(context.Background())
59	defer cancel()
60
61	go dialAndwriteQuicStream(ctx, "localhost", port, msg)
62
63	serverStreams := make(chan io.ReadWriteCloser)
64	go osp.RunQuicServer(ctx, port, *tlsCert, serverStreams)
65	serverStream := <-serverStreams
66	b := make([]byte, len(msg))
67	_, err = io.ReadFull(serverStream, b)
68	if err != nil {
69		log.Fatalln("Failed to read stream:", err.Error())
70	}
71	log.Println(string(b))
72}
73
74func testMessages() {
75	msg := osp.PresentationStartRequest{
76		RequestID:      1,
77		PresentationID: "This is a Presentation ID.  It must be very long.",
78		URL:            "https://github.com/webscreens/openscreenprotocol",
79	}
80
81	var rw bytes.Buffer
82	osp.WriteMessage(msg, &rw)
83	msg2, err := osp.ReadMessage(&rw)
84	if err != nil {
85		log.Fatalln("Failed to read message.");
86	}
87	log.Println(msg2)
88}
89
90func testVarint() {
91	n1 := uint64(12345)
92	rw := bytes.NewBuffer([]byte{})
93	log.Printf("Write: %d\n", n1)
94	err := osp.WriteVaruint(n1, rw)
95	if err != nil {
96		log.Fatalln("Failed to write varint", err.Error())
97	}
98	n2, err := osp.ReadVaruint(rw)
99	if err != nil {
100		log.Fatalln("Failed to read varint", err.Error())
101	}
102	log.Printf("Read: %d\n", n2)
103}
104
105func main() {
106	testVarint()
107	testMessages()
108	testQuic()
109	testMdns()
110}
111