本文整理汇总了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)
}
}
示例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)
}
示例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
}
}
}
示例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
}
示例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()
}()
}
示例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)
}
}
示例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,
})
}
}
}
}
示例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
}
示例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")
}
示例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)
}
}
示例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())
}
}
}
}
}
示例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)
}
示例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()
}
}
示例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()
}()
}
示例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
}
}
}
}