當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。