当前位置: 首页>>代码示例>>Golang>>正文


Golang Conn.Close方法代码示例

本文整理汇总了Golang中golang.org/x/net/websocket.Conn.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang Conn.Close方法的具体用法?Golang Conn.Close怎么用?Golang Conn.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在golang.org/x/net/websocket.Conn的用法示例。


在下文中一共展示了Conn.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Close

/**
 * Close connection
 */
func (server *server) Close(ws *websocket.Conn) {
	err := ws.Close()

	if err != nil {
		server.Error(err)
	}
}
开发者ID:stevejmason,项目名称:go-websockets,代码行数:10,代码来源:server.go

示例2: handle

// handle implements a WebSocket handler.
func (r *Reader) handle(ws *websocket.Conn) {
	encode := len(ws.Config().Protocol) > 0 && ws.Config().Protocol[0] == base64BinaryWebSocketProtocol
	defer close(r.err)
	defer ws.Close()
	go IgnoreReceives(ws, r.timeout)
	r.err <- messageCopy(ws, r.r, encode, r.ping, r.timeout)
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:8,代码来源:stream.go

示例3: 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
		}
	}
}
开发者ID:redsofa,项目名称:zmq-soundtouch,代码行数:32,代码来源:socketmanager.go

示例4: 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
}
开发者ID:cleblanc87,项目名称:rack,代码行数:60,代码来源:client.go

示例5: 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()
	}()

}
开发者ID:tomyhero,项目名称:battleship-game,代码行数:35,代码来源:server.go

示例6: 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)
	}
}
开发者ID:jollheef,项目名称:tin_foil_hat,代码行数:25,代码来源:scoreboard.go

示例7: 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,
				})
			}
		}
	}
}
开发者ID:andreinechaev,项目名称:MadRobotsServer,代码行数:27,代码来源:game.go

示例8: 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
}
开发者ID:vzex,项目名称:generic-deploy-system,代码行数:25,代码来源:httpserver.go

示例9: HandleConn

// HandleConn handles on an individual socket connection
func (s *SocketHandler) HandleConn(ws *websocket.Conn) {
	defer ws.Close()
	doneChan := make(chan bool, 1)
	s.connLock.Lock()
	s.connections = append(s.connections, &WebSocketConn{
		Conn:     ws,
		DoneChan: doneChan,
	})
	s.connLock.Unlock()
	s.newConnectionChan <- struct{}{}

	// read commands
forloop:
	for {
		select {
		case <-doneChan:
			break forloop
		default:
			var msg Command
			if err := websocket.JSON.Receive(ws, &msg); err != nil {
				if err == io.EOF {
					break forloop
				}
				fmt.Printf("\n[ERROR] %v", err)
			} else {
				s.commandChan <- msg
			}
		}
	}
	fmt.Printf("Done listening on socket")
}
开发者ID:yurigorokhov,项目名称:httpception,代码行数:32,代码来源:socket.go

示例10: Chat

func Chat(ws *websocket.Conn) {
	var message Message
	defer ws.Close()

	for {
		if err := websocket.JSON.Receive(ws, &message); err != nil {
			Log(err)
			return
		}

		active[message.Name] = ws

		if message.Text == "Register" {
			if err := websocket.JSON.Send(ws, online()); err != nil {
				Log(err)
				delete(active, message.Name)
				return
			}
			continue
		}

		go sendAll(&message)

	}
}
开发者ID:andreinechaev,项目名称:goMessengerApp,代码行数:25,代码来源:main.go

示例11: SockServer

func SockServer(ws *websocket.Conn) {
	var err error
	var clientMessage string
	// use []byte if websocket binary type is blob or arraybuffer
	// var clientMessage []byte
	defer func() {
		if err = ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		}
	}()

	client := ws.Request().RemoteAddr
	log.Println("Client connected:", client)
	sockCli := ClientConn{ws, client}
	ActiveClients[sockCli] = 0
	log.Println("Number of clients connected ...", len(ActiveClients))

	for {
		if err = Message.Receive(ws, &clientMessage); err != nil {
			log.Println("Websocket Disconnected waiting", err.Error())
			delete(ActiveClients, sockCli)
			log.Println("Number of clients still connected ...", len(ActiveClients))
			return
		}

		if len(clientMessage) > 0 {
			clientMessage = sockCli.clientIP + " Said: " + clientMessage
			for cs, _ := range ActiveClients {
				if err = Message.Send(cs.websocket, clientMessage); err != nil {
					log.Println("Could not send message to ", cs.clientIP, err.Error())
				}
			}
		}
	}
}
开发者ID:Chubik,项目名称:chat,代码行数:35,代码来源:chat.go

示例12: handle

// handle implements a WebSocket handler.
func (r *Reader) handle(ws *websocket.Conn) {
	// Close the connection when the client requests it, or when we finish streaming, whichever happens first
	closeConnOnce := &sync.Once{}
	closeConn := func() {
		closeConnOnce.Do(func() {
			ws.Close()
		})
	}

	negotiated := ws.Config().Protocol
	r.selectedProtocol = negotiated[0]
	defer close(r.err)
	defer closeConn()

	go func() {
		defer runtime.HandleCrash()
		// This blocks until the connection is closed.
		// Client should not send anything.
		IgnoreReceives(ws, r.timeout)
		// Once the client closes, we should also close
		closeConn()
	}()

	r.err <- messageCopy(ws, r.r, !r.protocols[r.selectedProtocol].Binary, r.ping, r.timeout)
}
开发者ID:astropuffin,项目名称:kubernetes,代码行数:26,代码来源:stream.go

示例13: Accept

func (s *Server) Accept(ws *websocket.Conn) {
	ws.PayloadType = websocket.BinaryFrame
	if _, err := NewConnection(s, ws); err != nil {
		ws.SetDeadline(time.Now().Add(2 * time.Millisecond))
		ws.Close()
	}
}
开发者ID:ethicatech,项目名称:tinybiome,代码行数:7,代码来源:websocket.go

示例14: wsserver

func wsserver(ws *websocket.Conn) {

	// read msg
	var (
		msg msgproto.Msg
		err error
		id  int32
		// topic string
	)
	for {
		err = msgCodec.Receive(ws, &msg)
		checkErr("Receive", err)
		if err != nil {
			break
		}
		// add client and topic client
		id = msg.GetId()
		if _, ok := clients[id]; !ok {
			clients[id] = ws
		}

		handleMsg(msg, ws)
	}

	defer func() {
		delete(clients, id)
		ws.Close()
	}()
}
开发者ID:Tang-RoseChild,项目名称:golang,代码行数:29,代码来源:server.go

示例15: HandleWS

// HandleWS implements a websocket handler.
func (w *WatchServer) HandleWS(ws *websocket.Conn) {
	defer ws.Close()
	done := make(chan struct{})
	go func() {
		var unused interface{}
		// Expect this to block until the connection is closed. Client should not
		// send anything.
		websocket.JSON.Receive(ws, &unused)
		close(done)
	}()
	for {
		select {
		case <-done:
			w.watching.Stop()
			return
		case event, ok := <-w.watching.ResultChan():
			if !ok {
				// End of results.
				return
			}
			w.fixup(event.Object)
			obj, err := watchjson.Object(w.codec, &event)
			if err != nil {
				// Client disconnect.
				w.watching.Stop()
				return
			}
			if err := websocket.JSON.Send(ws, obj); err != nil {
				// Client disconnect.
				w.watching.Stop()
				return
			}
		}
	}
}
开发者ID:johndmulhausen,项目名称:kubernetes,代码行数:36,代码来源:watch.go


注:本文中的golang.org/x/net/websocket.Conn.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。