本文整理汇总了Golang中golang.org/x/net/websocket.Conn类的典型用法代码示例。如果您正苦于以下问题:Golang Conn类的具体用法?Golang Conn怎么用?Golang Conn使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Conn类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Start
func (g *game) Start(ws *websocket.Conn) {
defer ws.Close()
var player user.User
for {
if err := websocket.JSON.Receive(ws, &player); err != nil {
panic(err)
return
}
player.Socket = ws
g.Players[player.Name] = player
for k, v := range g.Players {
if k == player.Name {
continue
}
if err := websocket.JSON.Send(v.Socket, player); err != nil {
delete(g.Players, k)
go g.SendMessageAll(&Message{
Method: "destroy",
UserName: k,
})
}
}
}
}
示例2: handleStatusWS
func handleStatusWS(conn *websocket.Conn) {
// log.Printf("Web client connected.\n")
timer := time.NewTicker(1 * time.Second)
for {
// The below is not used, but should be if something needs to be streamed from the web client ever in the future.
/* var msg SettingMessage
err := websocket.JSON.Receive(conn, &msg)
if err == io.EOF {
break
} else if err != nil {
log.Printf("handleStatusWS: %s\n", err.Error())
} else {
// Use 'msg'.
}
*/
// Send status.
<-timer.C
update, _ := json.Marshal(&globalStatus)
_, err := conn.Write(update)
if err != nil {
// log.Printf("Web client disconnected.\n")
break
}
}
}
示例3: ProcessRunAttached
func ProcessRunAttached(ws *websocket.Conn) *httperr.Error {
vars := mux.Vars(ws.Request())
header := ws.Request().Header
app := vars["app"]
process := vars["process"]
command := header.Get("Command")
release := header.Get("Release")
height, _ := strconv.Atoi(header.Get("Height"))
width, _ := strconv.Atoi(header.Get("Width"))
_, err := models.Provider().ProcessRun(app, process, structs.ProcessRunOptions{
Command: command,
Height: height,
Width: width,
Release: release,
Stream: ws,
})
if provider.ErrorNotFound(err) {
return httperr.New(404, err)
}
if err != nil {
return httperr.Server(err)
}
return nil
}
示例4: AppLogs
func AppLogs(ws *websocket.Conn) *httperr.Error {
app := mux.Vars(ws.Request())["app"]
header := ws.Request().Header
var err error
follow := true
if header.Get("Follow") == "false" {
follow = false
}
since := 2 * time.Minute
if s := header.Get("Since"); s != "" {
since, err = time.ParseDuration(s)
if err != nil {
return httperr.Errorf(403, "Invalid duration %s", s)
}
}
err = models.Provider().LogStream(app, ws, structs.LogStreamOptions{
Filter: header.Get("Filter"),
Follow: follow,
Since: time.Now().Add(-1 * since),
})
if err != nil {
if strings.HasSuffix(err.Error(), "write: broken pipe") {
return nil
}
return httperr.Server(err)
}
return nil
}
示例5: socketHandler
func socketHandler(ws *websocket.Conn) {
fmt.Println("In socketHandler" + ws.Request().RequestURI)
var msg DbgMessage
err := websocket.JSON.Receive(ws, &msg)
if err != nil {
fmt.Println("socketHandler: got error", err)
_ = websocket.Message.Send(ws, "FAIL:"+err.Error())
return
}
if msg.Command != "start" {
fmt.Println("socketHandler: terminating, 'start' expected.")
_ = websocket.Message.Send(ws, "FAIL: 'start' expected)")
return
}
var startMsg StartMessage
err = json.Unmarshal(msg.Payload, &startMsg)
if err != nil {
fmt.Println("socketHandler: wrong payload", err)
_ = websocket.Message.Send(ws, "FAIL:"+err.Error())
return
}
fmt.Println("socketHandler: received start message, exec = " + startMsg.Exec)
// Create communication channels.
fromProcess := make(chan string)
toProcess := make(chan string)
fromSocket := make(chan DbgMessage)
toSocket := make(chan string)
// Start processing the messages.
go process(fromProcess, toProcess, fromSocket, toSocket)
// Start the child process
go processHandler(fromProcess, toProcess)
// Launch a goroutine for sending messages through the websocket.
// TODO(jarin) Handle termination properly.
go func() {
for {
select {
case tosend := (<-toSocket):
err := websocket.Message.Send(ws, tosend)
if err != nil {
fmt.Println("socketHandler sender error", err)
return
}
}
}
}()
// Process incoming messages from the socket and pass them to the channel.
for {
err := websocket.JSON.Receive(ws, &msg)
if err != nil {
fmt.Println("socketHandler receive error", err)
return
}
fromSocket <- msg
}
}
示例6: echoHandler
func echoHandler(ws *websocket.Conn) {
var err error
var message Message
client := ClientConn{ws, ws.Request().RemoteAddr}
log.Println("Client connected:", client.ip)
for {
// получили сообщенько
if err = websocket.JSON.Receive(ws, &message); err != nil {
log.Println("Disconnected waiting", err.Error())
return
}
// разбираем, назначаем мастером того, кто так представился
if message.Data == "master" {
master = &client
log.Println("Master client:", master.ip)
continue
}
// если не мастера, то некому слать
if master == nil {
continue
}
// шлем то, что пришло, мастеру
if err = websocket.JSON.Send(master.ws, message); err != nil {
log.Println("Could not send message to ", master.ip, err.Error())
}
}
}
示例7: wsHandler
// wsHandler is a WebSocket server that handles requests from the WebSocket client in the form of:
// 1. { 'cmd': 'register', 'roomid': $ROOM, 'clientid': $CLIENT' },
// which binds the WebSocket client to a client ID and room ID.
// A client should send this message only once right after the connection is open.
// or
// 2. { 'cmd': 'send', 'msg': $MSG }, which sends the message to the other client of the room.
// It should be sent to the server only after 'regiser' has been sent.
// The message may be cached by the server if the other client has not joined.
//
// Unexpected messages will cause the WebSocket connection to be closed.
func (c *Collider) wsHandler(ws *websocket.Conn) {
var rid, cid string
registered := false
var msg wsClientMsg
loop:
for {
err := ws.SetReadDeadline(time.Now().Add(time.Duration(wsReadTimeoutSec) * time.Second))
if err != nil {
c.wsError("ws.SetReadDeadline error: "+err.Error(), ws)
break
}
err = websocket.JSON.Receive(ws, &msg)
if err != nil {
if err.Error() != "EOF" {
c.wsError("websocket.JSON.Receive error: "+err.Error(), ws)
}
break
}
switch msg.Cmd {
case "register":
if registered {
c.wsError("Duplicated register request", ws)
break loop
}
if msg.RoomID == "" || msg.ClientID == "" {
c.wsError("Invalid register request: missing 'clientid' or 'roomid'", ws)
break loop
}
if err = c.roomTable.register(msg.RoomID, msg.ClientID, ws); err != nil {
c.wsError(err.Error(), ws)
break loop
}
registered, rid, cid = true, msg.RoomID, msg.ClientID
c.dash.incrWs()
defer c.roomTable.deregister(rid, cid)
break
case "send":
if !registered {
c.wsError("Client not registered", ws)
break loop
}
if msg.Msg == "" {
c.wsError("Invalid send request: missing 'msg'", ws)
break loop
}
c.roomTable.send(rid, cid, msg.Msg)
break
default:
c.wsError("Invalid message: unexpected 'cmd'", ws)
break
}
}
// This should be unnecessary but just be safe.
ws.Close()
}
示例8: SystemLogs
// SystemLogs returns the logs for the Rack
func SystemLogs(ws *websocket.Conn) *httperr.Error {
header := ws.Request().Header
var err error
follow := true
if header.Get("Follow") == "false" {
follow = false
}
since := 2 * time.Minute
if s := header.Get("Since"); s != "" {
since, err = time.ParseDuration(s)
if err != nil {
return httperr.Errorf(403, "Invalid duration %s", s)
}
}
err = models.Provider().SystemLogs(ws, structs.LogStreamOptions{
Filter: header.Get("Filter"),
Follow: follow,
Since: time.Now().Add(-1 * since),
})
if err != nil {
return httperr.Server(err)
}
return nil
}
示例9: Stream
func (c *Client) Stream(path string, headers map[string]string, in io.Reader, out io.WriteCloser) error {
origin := fmt.Sprintf("https://%s", c.Host)
endpoint := fmt.Sprintf("wss://%s%s", c.Host, path)
config, err := websocket.NewConfig(endpoint, origin)
if err != nil {
return err
}
config.TlsConfig = &tls.Config{
InsecureSkipVerify: true,
}
config.Header.Set("Version", c.Version)
userpass := fmt.Sprintf("convox:%s", c.Password)
userpass_encoded := base64.StdEncoding.EncodeToString([]byte(userpass))
config.Header.Add("Authorization", fmt.Sprintf("Basic %s", userpass_encoded))
for k, v := range headers {
config.Header.Add(k, v)
}
config.TlsConfig = &tls.Config{
InsecureSkipVerify: true,
}
var ws *websocket.Conn
if proxy := os.Getenv("HTTPS_PROXY"); proxy != "" {
ws, err = c.proxyWebsocket(config, proxy)
} else {
ws, err = websocket.DialConfig(config)
}
if err != nil {
return err
}
defer ws.Close()
var wg sync.WaitGroup
if in != nil {
go io.Copy(ws, in)
}
if out != nil {
wg.Add(1)
go copyAsync(out, ws, &wg)
}
wg.Wait()
out.Close()
return nil
}
示例10: scoreboardHandler
func scoreboardHandler(ws *websocket.Conn) {
defer ws.Close()
fmt.Fprint(ws, currentResult)
sendedResult := currentResult
lastUpdate := time.Now()
for {
if sendedResult != currentResult ||
time.Now().After(lastUpdate.Add(time.Minute)) {
sendedResult = currentResult
lastUpdate = time.Now()
_, err := fmt.Fprint(ws, currentResult)
if err != nil {
log.Println("Socket closed:", err)
return
}
}
time.Sleep(time.Second)
}
}
示例11: wsOnConnect
func (this *socketManager) wsOnConnect(ws *websocket.Conn) {
var err error
var p payload
defer func() {
if err = ws.Close(); err != nil {
logger.Info.Println("Websocket could not be closed", err.Error())
}
}()
//Client connected to websocket
connection := connection{ws}
//Keep a reference to the connection
this.connections[&connection] = true
logger.Info.Println("WebSocket Connection event ...")
logger.Info.Println("Number of clients connected ...", len(this.connections))
//Get the last messages from the zmqDealer TCP pipe
this.getLastMessages(connection)
//Wait a bit for the last messages to send...
time.Sleep(3 * time.Second)
// Loop to keep websocket open
for {
if err = websocket.JSON.Receive(ws, &p); err != nil {
//Socket is closed if
logger.Info.Println("Websocket Disconnected...", err.Error())
//Remove connection from active connections
delete(this.connections, &connection)
logger.Info.Println("Number of clients connected ...", len(this.connections))
return
}
}
}
示例12: webSocketHandler
func (self *Server) webSocketHandler(conn *websocket.Conn) {
dispatcher := NewDispatcher(self)
for {
data := map[string]interface{}{}
err := websocket.JSON.Receive(conn, &data)
if err != nil {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
fmt.Println(err)
continue
}
if err == io.EOF {
fmt.Println(fmt.Sprintf("Client Dissconected :%s", conn.RemoteAddr()))
break
} else {
fmt.Println(fmt.Sprintf("Receive Data Failed %s", err))
break
}
}
fmt.Println("Dispatch", data)
err = dispatcher.Dispatch(conn, data)
if err != nil {
fmt.Println(fmt.Sprintf("Dispatch Failed %s", err))
}
}
defer func() {
conn.Close()
}()
}
示例13: BuildConnection
func BuildConnection(ws *websocket.Conn) {
email := ws.Request().URL.Query().Get("email")
if email == "" {
return
}
onlineUser := &OnlineUser{
InRoom: runningActiveRoom,
Connection: ws,
Send: make(chan Message, 256),
UserInfo: &User{
Email: email,
Name: strings.Split(email, "@")[0],
Gravatar: libs.UrlSize(email, 20),
},
}
runningActiveRoom.OnlineUsers[email] = onlineUser
m := Message{
MType: STATUS_MTYPE,
UserStatus: UserStatus{
Users: runningActiveRoom.GetOnlineUsers(),
},
}
runningActiveRoom.Broadcast <- m
go onlineUser.PushToClient()
onlineUser.PullFromClient()
onlineUser.killUserResource()
}
示例14: split
func split(data []byte, atEOF bool, conn *websocket.Conn, callback ReadCallBack) (adv int, token []byte, err error) {
l := len(data)
if l < 6 {
return 0, nil, nil
}
if l > 100000 {
conn.Close()
log.Println("invalid query!")
return 0, nil, errors.New("to large data!")
}
var len1, len2 int
len1 = int(binary.LittleEndian.Uint16(data[:2]))
len2 = int(binary.LittleEndian.Uint32(data[2:6]))
offset := 0
if len1+len2+6 > l {
conn.Close()
log.Println("invalid data", len1, len2, l)
return 0, nil, errors.New("invalid data")
}
offset += len1 + len2 + 6
head := string(data[6 : 6+len1])
tail := data[6+len1 : 6+len1+len2]
callback(conn, head, tail)
return offset, []byte{}, nil
}
示例15: BuildConnection
func BuildConnection(ws *websocket.Conn) {
log.Info("BuildConnection()")
token := ws.Request().URL.Query().Get("token")
log.Debug(token)
var uci userConnectionInfo
err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("validation error")
// how should this reply to the client?
return
}
onlineUser := &OnlineUser{
Connection: ws,
Uci: uci,
Send: make(chan envelope, 256),
}
runningRoom.Users[onlineUser] = true
go onlineUser.PushToClient()
onlineUser.PullFromClient()
delete(runningRoom.Users, onlineUser)
log.Info("tore down user connection")
}