本文整理匯總了Golang中websocket.Conn.Close方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.Close方法的具體用法?Golang Conn.Close怎麽用?Golang Conn.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類websocket.Conn
的用法示例。
在下文中一共展示了Conn.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: handleWebSocket
func handleWebSocket(conn *websocket.Conn) {
respStatus := http.StatusOK
defer func() {
conn.Close()
logRequest(HTTPS_WEBSOCKET, respStatus, conn.Request().Host, conn.Request())
}()
request := make([]byte, 1024)
for {
n, err := conn.Read(request)
if err != nil {
if debugMode {
log.Error("Error reading on WebSocket: %s", err)
}
break
}
response, status := getLiveItems(string(request[:n]))
if status != http.StatusOK {
respStatus = status
break
}
if len(response) != 0 {
if _, err = conn.Write(response); err != nil {
break
}
}
}
}
示例2: clientHandler
func clientHandler(ws *websocket.Conn) {
defer func() {
subscriptionChan <- subscription{ws, false}
ws.Close()
}()
subscriptionChan <- subscription{ws, true}
for {
buf := make([]byte, 128)
n, err := ws.Read(buf)
if err != nil {
log.Print("Reading Buffer: ", err)
break
}
var m message
err = json.Unmarshal(buf[0:n], &m)
if err != nil {
log.Print("Parsing JSON: ", buf, m, err)
break
}
messageChan <- message{m.Text, m.Id, m.User, m.Command}
}
}
示例3: LobbyServer
func LobbyServer(ws *websocket.Conn) {
reader := bufio.NewReader(ws)
var username string
var player *Player
connected := false
sendPlayers(ws)
inGame := false
for {
br, er := reader.ReadString('\n')
if er == os.EOF {
break
}
msg := strings.Split(br, " ")
switch msg[0] {
case "connect":
username = strings.TrimSpace(msg[1])
if _, ok := users[username]; !ok && !connected {
player = &Player{Name: username, Socket: ws}
sendPlayer(player)
users[username] = player
fmt.Printf("Got connection from %s\n", username)
connected = true
} else {
fmt.Fprint(ws, "error Username Exists")
ws.Close()
return
}
case "create":
if inGame {
fmt.Fprint(ws, "error Already in a game")
continue
}
fmt.Printf("Create %s\n", username)
sendPlayer(player)
inGame = true
continue
case "start":
fmt.Printf("Game %s\n", br)
for _, info := range users {
fmt.Fprintf(info.Socket, "Game %s", "start")
}
case "point":
user := strings.TrimSpace(msg[1])
point, _ := strconv.Atoi(strings.TrimSpace(msg[2]))
player = &Player{Name: user, Point: point, Socket: ws}
sendPlayer(player)
users[username] = player
continue
default:
fmt.Printf("Unknown message: %s\n", br)
}
}
}
示例4: clientHandler
/*
* Get messages from client
*/
func clientHandler(ws *websocket.Conn) {
defer func() {
log.Println("Client handler closed.")
ws.Close()
}()
buf := make([]byte, 256)
stopCh := make(chan bool)
var input ProcessInput
for {
n, err := ws.Read(buf)
if err != nil {
break
}
// get data
err = json.Unmarshal(buf[0:n], &input)
if err != nil {
stopCh <- true
break
}
workChan <- Work{ws, &input, stopCh}
}
}
示例5: throwFatal
func throwFatal(ws *websocket.Conn, reason string) {
msg := message{
Channel: "",
Data: map[string]string{
"response": "error",
"reason": reason,
},
Auth: Auth{},
Mode: "error",
}
websocket.JSON.Send(ws, msg)
unsubscribe(ws)
ws.Close()
}
示例6: Handle
func Handle(ws *websocket.Conn) {
fmt.Println("New Connection.")
encoder := json.NewEncoder(ws)
i := 0
for _, line := range lines {
i++
if i > 47 {
time.Sleep(time.Duration((rand.Intn(2000) + 700) * int(time.Millisecond)))
}
data := struct{ Server, Line string }{"irc.foonetic.net", line}
encoder.Encode(data)
}
fmt.Println("Conn closed.")
ws.Close()
}
示例7: subscribe
func (m *model) subscribe(s *websocket.Conn) {
data, err := json.MarshalIndent(newConnectMessage(m.Changes, m.Kittens, m.VersionIdentifier), "", " ")
if err != nil {
s.Close()
return
}
_, err = s.Write(data)
if err != nil {
s.Close()
return
}
m.Conns[s] = 1
}
示例8: clientHandler
func clientHandler(ws *websocket.Conn) {
defer func() {
subscriptionChan <- subscription{ws, false}
ws.Close()
}()
subscriptionChan <- subscription{ws, true}
buf := make([]byte, 256)
for {
n, err := ws.Read(buf)
if err != nil {
break
}
messageChan <- buf[0:n]
}
}
示例9: SocketServer
func SocketServer(ws *websocket.Conn) {
c := make(chan []byte, 100)
e := ws_channels.PushBack(c)
fmt.Printf("New connection: %v total\n", ws_channels.Len())
var data []byte
for {
select {
case data = <-c:
case <-time.After(5e9): // make sure we're still connected
data = []byte("")
}
if _, err := ws.Write(data); err != nil {
// fmt.Println("Closing")
ws.Close()
break
}
}
ws_channels.Remove(e)
fmt.Printf("Closed connection: %v total\n", ws_channels.Len())
}
示例10: wsHandler
func wsHandler(ws *websocket.Conn) {
defer func() {
unsubscribe(ws)
ws.Close()
}()
subscribe(ws)
for { // loop forEVER
var data message
err := websocket.JSON.Receive(ws, &data)
if err != nil {
log.Print("wsHandler > websocket.JSON.Receive: " + err.Error())
break
}
if data.Channel != "" {
setChannel(ws, data.Channel)
} else {
throwFatal(ws, "Must specify a Channel name")
}
if data.Auth.User != "" {
log.Print(data.Auth)
auth, err := checkAPIAuth(data.Auth.User, data.Auth.Secret)
if err != nil {
throwFatal(ws, "Server error. Please try again later.")
} else {
if auth {
if device := strings.Split(data.Channel, "/"); device[0] != data.Auth.User {
throwFatal(ws, "Unauthorised use of device.")
} else {
authorise(ws, data.Auth.User, data.Auth.Secret)
messageChan <- data
}
} else {
throwFatal(ws, "Auth parameters invalid.")
}
}
}
}
}
示例11: doEventStream
func doEventStream(ws *websocket.Conn) {
ID := chat.UUID()
defer func() {
subscriptionChan <- &Subscription{ws, chat.REMOVE_CONNECTION, &User{ID, nil, ""}}
ws.Close()
}()
subscriptionChan <- &Subscription{ws, chat.ADD_CONNECTION, &User{ID, nil, ""}}
newStartMessage, _ := json.Marshal(
MessageData{
"start",
map[string]interface{}{
"ID": ID,
}})
ws.Write(newStartMessage)
for {
buf := make([]byte, 1024)
n, err := ws.Read(buf)
if err != nil {
log.Println("Error reading from websocket connection: ", err.Error())
break
}
newMessageData := new(MessageData)
err = json.Unmarshal(buf[0:n], newMessageData)
if err != nil {
log.Println("Error unmarshaling message: ", string(buf[0:n]), " : ", err.Error())
}
messageChan <- message{
ws,
*newMessageData,
}
}
}
示例12: liveReload16ConnectionHandler
func liveReload16ConnectionHandler(ws *websocket.Conn) {
defer func() {
subscriptionChannel <- subscriptionMessage{ws, false, ""}
fmt.Printf("Browser disconnected")
ws.Close()
}()
websocket.Message.Send(ws, fmt.Sprintf("!!ver:%s", API_VERSION))
fmt.Printf("Browser Connected")
// on connection it's the client url
var onConnectionMessage string
websocket.Message.Receive(ws, &onConnectionMessage)
subscriptionChannel <- subscriptionMessage{ws, true, onConnectionMessage}
fmt.Printf("Browser URL: %s", onConnectionMessage)
// websocket messages from the clients get pushed though the eventhub
for {
var msg string
websocket.Message.Receive(ws, &msg)
messageChannel <- msg
}
}
示例13: broadcastHandler
func broadcastHandler(ws *websocket.Conn) {
defer func() {
subscriptionChan <- subscription{ws, false}
ws.Close()
fmt.Printf("Closed \n")
}()
fmt.Printf("Adding to subscription \n")
subscriptionChan <- subscription{ws, true}
fmt.Printf("Added to subscription \n")
buf := make([]byte, 256)
for {
n, err := ws.Read(buf)
fmt.Printf("Reding message %v \n", n)
if err != nil {
break
}
messageChan <- buf[0:n]
}
}
示例14: doEventStream
func doEventStream(ws *websocket.Conn) {
defer func() {
subscriptionChan <- subscription{ws, false}
ws.Close()
}()
subscriptionChan <- subscription{ws, true}
for {
buf := make([]byte, 512)
n, err := ws.Read(buf)
if err != nil {
log.Println("Error reading from websocket connection")
break
}
messageChan <- message{
ws,
buf[0:n],
}
}
}
示例15: TestAllTheThings
func TestAllTheThings(t *testing.T) {
var ws *websocket.Conn
var req net.Conn
var wss [5]*websocket.Conn
ws = websocketDial(t)
testWebsocketConnect(t, ws)
testWebsocketBadRequests(t, ws)
testWebsocketAuthenticationWithoutToken(t, ws)
testWebsocketAuthenticationWithInvalidTokenFormat(t, ws)
testWebsocketAuthenticationWithInvalidToken(t, ws)
testWebsocketAuthenticationWithValidToken(t, ws)
testWebsocketSubscribeWithoutChannelName(t, ws)
testWebsocketSubscribeWithEmptyChannelName(t, ws)
testWebsocketSubscribeWithInvalidChannelName(t, ws)
testWebsocketSubscribeToNotExistingChannel(t, ws)
testWebsocketUnsubscribeWithoutChannelName(t, ws)
testWebsocketUnsubscribeWithEmptyChannelName(t, ws)
testWebsocketUnsubscribeWithInvalidChannelName(t, ws)
testWebsocketUnsubscribeNotSubscribedChannel(t, ws)
ws.Close()
ws = websocketDial(t)
testWebsocketConnect(t, ws)
testWebsocketSubscribeToPublicChannel(t, ws)
testWebsocketUnsubscribeSubscribedChannel(t, ws)
testWebsocketSubscribeToPrivateChannelWithoutAuthentication(t, ws)
testWebsocketSubscribeToPresenceChannelWithoutAuthentication(t, ws)
testWebsocketAuthenticationWithValidToken(t, ws)
testWebsocketSubscribeToPrivateChannelWithAuthentication(t, ws)
testWebsocketSubscribeToPresenceChannelWithAuthentication(t, ws)
ws.Close()
for i := range wss {
wss[i] = websocketDial(t)
testWebsocketConnect(t, wss[i])
testWebsocketAuthenticationWithValidToken(t, wss[i])
}
testWebsocketPresenceChannelSubscribeBehaviour(t, wss[:])
testWebsocketPresenceChannelUnsubscribeBehaviour(t, wss[:])
for i := range wss {
wss[i].Close()
wss[i] = nil
}
ws = websocketDial(t)
testWebsocketConnect(t, ws)
testWebsocketBroadcastWithoutChannelSpecified(t, ws)
testWebsocketBroadcastWithEmptyChannelSpecified(t, ws)
testWebsocketBroadcastWithoutEventSpecified(t, ws)
testWebsocketBroadcastToNotSubscribedChannel(t, ws)
testWebsocketBroadcastToNotExistingChannel(t, ws)
ws.Close()
for i := range wss {
wss[i] = websocketDial(t)
testWebsocketConnect(t, wss[i])
testWebsocketSubscribeToPublicChannel(t, wss[i])
}
testWebsocketBroadcast(t, wss[:])
testBackendBroadcast(t, req, wss[:])
for i := range wss {
wss[i].Close()
wss[i] = nil
}
testBackendBadRequest(t, req)
testBackendBadIdentity(t, req)
testBackendOpenChannelWithoutName(t, req)
testBackendOpenChannelWithInvalidName(t, req)
testBackendOpenExistingChannel(t, req)
testBackendOpenNewChannel(t, req)
testBackendCloseChannelWithoutName(t, req)
testBackendCloseChannelWithInvalidName(t, req)
testBackendCloseNotExistingChannel(t, req)
testBackendRequestSingleAccessTokenWithoutPermission(t, req)
testBackendRequestSingleAccessTokenWithInvalidPermission(t, req)
testBackendRequestSingleAccessTokenWithValidPermission(t, req)
testBackendBroadcastWithEmptyChannelName(t, req)
testBackendBroadcastWithEmptyEventName(t, req)
testBackendBroadcastToNotExistingChannel(t, req)
testBackendBroadcastWithInvalidData(t, req)
}