コード例 #1
0
ファイル: gamelist.go プロジェクト: zclark/wdead
func (l *GameList) Attached() {
	ws, err := websocket.New("ws://apppath:8000/ws/game")
	if err != nil {
		log.Fatalf("Failed to connect to socket: %s", err.Error())
	}

	ws.AddEventListener("open", false, l.onOpen)
	ws.AddEventListener("message", false, l.onMessage)
	ws.AddEventListener("close", false, l.onClose)
	ws.AddEventListener("error", false, l.onError)

	l.Skt = ws
}
コード例 #2
0
ファイル: frontend.go プロジェクト: andreas-jonsson/octatron
func setupConnection(gl *webgl.Context) {
	document := js.Global.Get("document")
	location := document.Get("location")

	ws, err := websocket.New(fmt.Sprintf("ws://%s/render", location.Get("host")))
	assert(err)

	renderer := make(chan struct{})

	onOpen := func(ev *js.Object) {
		setup := setupMessage{
			Resolution: imgCmResolution,
			ClearColor: [4]byte{127, 127, 127, 255},
		}

		msg, err := json.Marshal(setup)
		assert(err)

		assert(ws.Send(string(msg)))

		go updateCamera(ws, gl, renderer)
	}

	onMessage := func(ev *js.Object) {
		face := frameId % 6
		fmt.Println("Received face:", face)

		data := js.Global.Get("Uint8Array").New(ev.Get("data"))
		gl.Call("texImage2D", gl.TEXTURE_CUBE_MAP_POSITIVE_X+face, 0, gl.RGBA, imgCmResolution, imgCmResolution, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
		frameId++

		select {
		case renderer <- struct{}{}:
		default:
		}
	}

	ws.BinaryType = "arraybuffer"
	ws.AddEventListener("open", false, onOpen)
	ws.AddEventListener("message", false, onMessage)
}
コード例 #3
0
ファイル: client.go プロジェクト: MJKWoolnough/gopherjs
// Dial connects a websocket to the given address and creates the client
func Dial(addr string) (*Client, error) {
	w, err := websocket.New(addr)
	if err != nil {
		return nil, err
	}
	reqs := make(map[uint]func(json.RawMessage, error))
	w.AddEventListener("message", false, func(e *js.Object) {
		var (
			r request
			m json.RawMessage
		)
		r.Params[0] = &m
		err := json.UnmarshalString(e.Get("data").String(), &r)
		f, ok := reqs[r.ID]
		if ok {
			delete(reqs, r.ID)
			go f(m, err)
		}
	})
	return &Client{
		ws:   w,
		reqs: reqs,
	}, nil
}
コード例 #4
0
ファイル: frontend.go プロジェクト: andreas-jonsson/octatron
func setupConnection() {
	ctx := canvas.Call("getContext", "2d")
	img := ctx.Call("getImageData", 0, 0, imgWidth, imgHeight)

	if img.Get("data").Length() != len(finalImage.Pix) {
		throw(errors.New("data size of images do not match"))
	}

	document := js.Global.Get("document")
	location := document.Get("location")

	ws, err := websocket.New(fmt.Sprintf("ws://%s/render", location.Get("host")))
	assert(err)

	renderChan := make(chan struct{}, frameStacking)

	onOpen := func(ev *js.Object) {
		setup := setupMessage{
			Width:       imgWidth,
			Height:      imgHeight,
			FieldOfView: 45,
			ColorFormat: colorFormat,
			ClearColor:  [4]byte{127, 127, 127, 255},
		}

		msg, err := json.Marshal(setup)
		assert(err)

		assert(ws.Send(string(msg)))

		go updateCamera(ws, renderChan)
	}

	onMessage := func(ev *js.Object) {
		idx := frameId % 2
		data := js.Global.Get("Uint8Array").New(ev.Get("data")).Interface().([]uint8)

		if isPalette(data) {
			pal := createPalette(data)
			palImages = [2]*image.Paletted{
				image.NewPaletted(imgRect, pal),
				image.NewPaletted(imgRect, pal),
			}
			return
		}

		var (
			imageA, imageB image.Image
		)

		if isRGBA(data) {
			rgbaImages[idx].Pix = data
			imageA = rgbaImages[0]
			imageB = rgbaImages[1]
		} else {
			palImages[idx].Pix = data
			imageA = palImages[0]
			imageB = palImages[1]
		}

		// This function could be optimized for this specific senario.
		assert(trace.Reconstruct(imageA, imageB, finalImage))

		arrBuf := js.NewArrayBuffer(finalImage.Pix)
		buf := js.Global.Get("Uint8ClampedArray").New(arrBuf)
		img.Get("data").Call("set", buf)
		ctx.Call("putImageData", img, 0, 0)

		numFrames++
		frameId++

		renderChan <- struct{}{}
	}

	ws.BinaryType = "arraybuffer"
	ws.AddEventListener("open", false, onOpen)
	ws.AddEventListener("message", false, onMessage)
}
コード例 #5
0
ファイル: index.go プロジェクト: snyderep/pongish
func main() {
	wsBaseURL := getWSBaseURL()

	qunit.Module("websocket.WebSocket")
	qunit.Test("Invalid URL", func(assert qunit.QUnitAssert) {
		qunit.Expect(1)

		ws, err := websocket.New("blah://blah.example/invalid")
		if err == nil {
			ws.Close()
			assert.Ok(false, "Got no error, but expected an invalid URL error")
			return
		}

		assert.Ok(true, fmt.Sprintf("Received an error: %s", err))
	})
	qunit.AsyncTest("Immediate close", func() interface{} {
		qunit.Expect(2)

		ws, err := websocket.New(wsBaseURL + "immediate-close")
		if err != nil {
			qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err))
			qunit.Start()
			return nil
		}

		ws.AddEventListener("open", false, func(ev *js.Object) {
			qunit.Ok(true, "WebSocket opened")
		})

		ws.AddEventListener("close", false, func(ev *js.Object) {
			const (
				CloseNormal            = 1000
				CloseNoReasonSpecified = 1005 // IE10 hates it when the server closes without sending a close reason
			)
			closeEvent := dom.WrapEvent(ev).(*dom.CloseEvent)
			if closeEvent.Code != CloseNormal && closeEvent.Code != CloseNoReasonSpecified {
				qunit.Ok(false, fmt.Sprintf("WebSocket close was not clean (code %d)", closeEvent.Code))
				qunit.Start()
				return
			}
			qunit.Ok(true, "WebSocket closed")
			qunit.Start()
		})

		return nil
	})

	qunit.Module("websocket.Conn")
	qunit.AsyncTest("Immediate close", func() interface{} {
		go func() {
			defer qunit.Start()

			ws, err := websocket.Dial(wsBaseURL + "immediate-close")
			if err != nil {
				qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err))
				return
			}

			qunit.Ok(true, "WebSocket opened")

			_, err = ws.Read(nil)
			if err == io.EOF {
				qunit.Ok(true, "Received EOF")
			} else if err != nil {
				qunit.Ok(false, fmt.Sprintf("Unexpected error in second read: %s", err))
			} else {
				qunit.Ok(false, "Expected EOF in second read, got no error")
			}
		}()

		return nil
	})
	qunit.AsyncTest("Failed open", func() interface{} {
		go func() {
			defer qunit.Start()

			ws, err := websocket.Dial(wsBaseURL + "404-not-found")
			if err == nil {
				ws.Close()
				qunit.Ok(false, "Got no error, but expected an error in opening the WebSocket.")
				return
			}

			qunit.Ok(true, fmt.Sprintf("WebSocket failed to open: %s", err))
		}()

		return nil
	})
	qunit.AsyncTest("Binary read", func() interface{} {
		qunit.Expect(3)

		go func() {
			defer qunit.Start()

			ws, err := websocket.Dial(wsBaseURL + "binary-static")
			if err != nil {
				qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err))
				return
			}

			qunit.Ok(true, "WebSocket opened")

			var expectedData = []byte{0x00, 0x01, 0x02, 0x03, 0x04}

			receivedData := make([]byte, len(expectedData))
			n, err := ws.Read(receivedData)
			if err != nil {
				qunit.Ok(false, fmt.Sprintf("Error in first read: %s", err))
				return
			}
			receivedData = receivedData[:n]

			if !bytes.Equal(receivedData, expectedData) {
				qunit.Ok(false, fmt.Sprintf("Received data did not match expected data. Got % x, expected % x.", receivedData, expectedData))
			} else {
				qunit.Ok(true, fmt.Sprintf("Received data: % x", receivedData))
			}

			_, err = ws.Read(receivedData)
			if err == io.EOF {
				qunit.Ok(true, "Received EOF")
			} else if err != nil {
				qunit.Ok(false, fmt.Sprintf("Unexpected error in second read: %s", err))
			} else {
				qunit.Ok(false, "Expected EOF in second read, got no error")
			}
		}()

		return nil
	})
	qunit.AsyncTest("Timeout", func() interface{} {
		qunit.Expect(2)

		go func() {
			defer qunit.Start()

			ws, err := websocket.Dial(wsBaseURL + "wait-30s")
			if err != nil {
				qunit.Ok(false, fmt.Sprintf("Error opening WebSocket: %s", err))
				return
			}

			qunit.Ok(true, "WebSocket opened")

			start := time.Now()
			ws.SetReadDeadline(start.Add(1 * time.Second))

			_, err = ws.Read(nil)
			if err != nil && err.Error() == "i/o timeout: deadline reached" {
				totalTime := time.Now().Sub(start)
				if totalTime < 750*time.Millisecond {
					qunit.Ok(false, fmt.Sprintf("Timeout was too short: Received timeout after %s", totalTime))
					return
				}
				qunit.Ok(true, fmt.Sprintf("Received timeout after %s", totalTime))
			} else if err != nil {
				qunit.Ok(false, fmt.Sprintf("Unexpected error in read: %s", err))
			} else {
				qunit.Ok(false, "Expected timeout in read, got no error")
			}
		}()

		return nil
	})
}