websocket

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 17, 2021 License: MIT Imports: 17 Imported by: 4

README

websocket

PkgGoDev Build Status Go Report Card LICENSE

Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.

Feature

Benchmark

websocket-qpswebsocket-p99

Get started

Install
go get github.com/hslam/websocket
Import
import "github.com/hslam/websocket"
Usage
Example

server.go

package main

import (
	"github.com/hslam/mux"
	"github.com/hslam/websocket"
	"log"
	"net/http"
	"strings"
)

func main() {
	m := mux.New()
	m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		conn, err := websocket.UpgradeHTTP(w, r)
		if err != nil {
			return
		}
		for {
			var message string
			err := conn.ReceiveMessage(&message)
			if err != nil {
				break
			}
			conn.SendMessage(strings.ToUpper(string(message)))
		}
		conn.Close()
	}).GET()
	log.Fatal(http.ListenAndServe(":8080", m))
}

server_poll.go

package main

import (
	"github.com/hslam/netpoll"
	"github.com/hslam/websocket"
	"net"
	"strings"
)

func main() {
	var handler = &netpoll.ConnHandler{}
	handler.SetUpgrade(func(conn net.Conn) (netpoll.Context, error) {
		return websocket.Upgrade(conn, nil)
	})
	handler.SetServe(func(context netpoll.Context) error {
		ws := context.(*websocket.Conn)
		var message string
		err := ws.ReceiveMessage(&message)
		if err != nil {
			return err
		}
		return ws.SendMessage(strings.ToUpper(string(message)))
	})
	if err := netpoll.ListenAndServe("tcp", ":8080", handler); err != nil {
		panic(err)
	}
}

client.go

package main

import (
	"fmt"
	"github.com/hslam/websocket"
	"time"
)

func main() {
	conn, err := websocket.Dial("tcp", "127.0.0.1:8080", "/", nil)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	for i := 0; i < 1; i++ {
		conn.SendMessage("Hello World")
		var message string
		err := conn.ReceiveMessage(&message)
		if err != nil {
			break
		}
		fmt.Println(message)
		time.Sleep(time.Second)
	}
}

Output

HELLO WORLD

client.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Websocket</title>
</head>
<body>
<h1>UPPER</h1>
<form><p>string: <input id="content" type="text" placeholder="input string"></p></form>
<label id="result">result:</label><br><br>
<button onclick="send()">upper</button>
<script type="text/javascript">
    var wsuri = "ws://127.0.0.1:8080/";
    var ws = new WebSocket(wsuri);
    ws.onmessage = function(e) {
        var result = document.getElementById('result');
        result.innerHTML = "result:" + e.data;
    }
    function send() {
        var msg = document.getElementById('content').value;
        ws.send(msg);
    }
</script>
</body>
</html>
License

This package is licensed under a MIT license (Copyright (c) 2020 Meng Huang)

Author

websocket was written by Meng Huang.

Documentation

Overview

Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.

Index

Constants

View Source
const (
	// ContinuationFrame represents a WebSocket continuation frame.
	ContinuationFrame = 0x0
	// TextFrame represents a WebSocket text frame.
	TextFrame = 0x1
	// BinaryFrame represents a WebSocket binary frame.
	BinaryFrame = 0x2
	// CloseFrame represents a WebSocket close frame.
	CloseFrame = 0x8
	// PingFrame represents a WebSocket ping frame.
	PingFrame = 0x9
	// PongFrame represents a WebSocket pong frame.
	PongFrame = 0xA
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn represents a WebSocket connection.

func Dial

func Dial(network, address, path string, config *tls.Config) (*Conn, error)

Dial opens a new client connection to a WebSocket.

func Upgrade

func Upgrade(conn net.Conn, config *tls.Config) (*Conn, error)

Upgrade upgrades the net.Conn conn to the WebSocket protocol.

func UpgradeHTTP

func UpgradeHTTP(w http.ResponseWriter, r *http.Request) (*Conn, error)

UpgradeHTTP upgrades the HTTP server connection to the WebSocket protocol.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

func (*Conn) Read

func (c *Conn) Read(b []byte) (n int, err error)

Read implements the net.Conn Read method.

func (*Conn) ReadMessage

func (c *Conn) ReadMessage(buf []byte) (p []byte, err error)

ReadMessage reads single message from ws.

func (*Conn) ReadTextMessage

func (c *Conn) ReadTextMessage() (p string, err error)

ReadTextMessage reads single text message from ws.

func (*Conn) ReceiveMessage

func (c *Conn) ReceiveMessage(v interface{}) (err error)

ReceiveMessage receives single frame from ws, unmarshaled and stores in v.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

func (*Conn) SendMessage

func (c *Conn) SendMessage(v interface{}) (err error)

SendMessage sends v marshaled as single frame to ws.

func (*Conn) SetConcurrency

func (c *Conn) SetConcurrency(concurrency func() int)

SetConcurrency sets a callback func concurrency for writer.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline implements the Conn SetDeadline method.

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*Conn) Write

func (c *Conn) Write(b []byte) (n int, err error)

Write implements the net.Conn Write method.

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(b []byte) (err error)

WriteMessage writes single message to ws.

func (*Conn) WriteTextMessage

func (c *Conn) WriteTextMessage(b string) (err error)

WriteTextMessage writes single text message to ws.

type Handler

type Handler func(*Conn)

Handler represents a http.Handler.

func (Handler) ServeHTTP

func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface for a WebSocket

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL