本文整理汇总了Golang中websocket.Conn类的典型用法代码示例。如果您正苦于以下问题:Golang Conn类的具体用法?Golang Conn怎么用?Golang Conn使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Conn类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: 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}
}
}
开发者ID:matt-west,项目名称:gochat,代码行数:26,代码来源:chat.go
示例2: 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
}
}
}
}
开发者ID:elimisteve,项目名称:togethr,代码行数:27,代码来源:live-server.go
示例3: 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}
}
}
开发者ID:egonelbre,项目名称:sivq,代码行数:28,代码来源:server.go
示例4: 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)
}
}
}
开发者ID:uglybrd,项目名称:GoGameHTML5,代码行数:60,代码来源:server.go
示例5: HandleWebsocket
// handle receives messages on the given websocket connection, decoding them
// from JSON to a Msg object. It adds a channel to listeners, encoding messages
// received on the listener channel as JSON, then sending it over the connection.
func (r *Router) HandleWebsocket(c *websocket.Conn) {
u, err := url.Parse(c.LocalAddr().String())
if err != nil {
log.Println(err)
return
}
// split url path into components, e.g.
// url: http://leeps.ucsc.edu/redwood/session/1/[email protected]
// path: /redwood/session/1/[email protected]
// -> [redwood, session, 1, [email protected]]
components := strings.Split(u.Path, "/")
// map components into instance_prefix, session_id, and subject_name
var instance, session_id_string, subject_name string
if len(components) >= 4 {
instance = components[1]
session_id_string = components[2]
subject_name = components[3]
} else {
session_id_string = components[1]
subject_name = components[2]
}
session_id, err := strconv.Atoi(session_id_string)
if err != nil {
log.Println(err)
return
}
var subject *Subject
if subject_name == "admin" || subject_name == "listener" {
subject = &Subject{name: subject_name, period: -1, group: -1}
} else {
// put in a request to the server loop for the given subject object
// this ensures only one subject object exists per session/name pair
request := &SubjectRequest{instance: instance, session: session_id, name: subject_name, response: make(chan *Subject)}
r.requestSubject <- request
subject = <-request.response
}
if subject == nil {
log.Panicln("nil subject")
}
listener := NewListener(r, instance, session_id, subject, c)
ack := make(chan bool)
r.newListeners <- &ListenerRequest{listener, ack}
// wait for listener to be registered before starting sync
<-ack
log.Printf("STARTED SYNC: %s\n", subject.name)
listener.Sync()
log.Printf("FINISHED SYNC: %s\n", subject.name)
go listener.SendLoop()
listener.ReceiveLoop()
}
开发者ID:RedwoodAdmin,项目名称:RedwoodFramework,代码行数:60,代码来源:router.go
示例6: IsClosed
func IsClosed(ws *websocket.Conn) bool {
var ibuff [50]byte
_, err := ws.Read(ibuff[0:50])
if err != nil {
return true
}
return false
}
开发者ID:hpcorona,项目名称:webtalk,代码行数:10,代码来源:main.go
示例7: ReadThread
func ReadThread(ws *websocket.Conn, msg []byte, ch chan int) {
for {
n, error := ws.Read(msg)
if error != nil {
fmt.Println("WebSocket read error: ", error)
ch <- 0
break
}
ch <- n
if n == 0 {
break
}
}
}
开发者ID:Saikees,项目名称:practice,代码行数:14,代码来源:websocket.go
示例8: 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()
}
开发者ID:klinster,项目名称:Bessie,代码行数:14,代码来源:websockets.go
示例9: 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()
}
开发者ID:CasualSuperman,项目名称:GoIRC,代码行数:15,代码来源:goirc.go
示例10: sub
func sub(ws *websocket.Conn) {
println("Beginning Sub")
var resp = make([]byte, 512)
for {
println("Waiting Read")
_, err := ws.Read(resp)
if err != nil {
panic(err)
}
// fmt.Println("Received 1:", string(resp[0:n]))
// fmt.Println("Received %v:", n)
ch <- 1
}
}
开发者ID:blindsey,项目名称:wsbench,代码行数:16,代码来源:broadcast_client.go
示例11: handler
func handler(ws *websocket.Conn) {
x := 0.
for {
if x >= 2*math.Pi {
x = 0
} else {
x += 0.05
}
time.Sleep(500 * 1000 * 1000) // sleep for 500ms (Sleep takes nanoseconds)
msg := strconv.Ftoa64(math.Sin(x), 'g', 10)
log.Printf("%v sending: %v\n", ws, msg)
ws.Write([]byte(msg))
}
}
开发者ID:svenlange,项目名称:websocket,代码行数:16,代码来源:server.go
示例12: doWebSocket
/*
websocket接收发送消息
*/
func doWebSocket(w http.ResponseWriter, r *http.Request, conn *websocket.Conn) {
for {
var inputData []byte
msgType, inputData, err := conn.ReadMessage()
if err != nil {
logger.Println(tag_customRoute, err)
return
}
logger.Println(tag_customRoute, "receive data:"+string(inputData))
err = conn.WriteMessage(msgType, inputData)
if err != nil {
logger.Println(tag_customRoute, err)
return
}
}
}
开发者ID:zhangxx110,项目名称:SimpleForumByGo,代码行数:19,代码来源:customRoute.go
示例13: 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]
}
}
开发者ID:ngd,项目名称:chrome-bench,代码行数:17,代码来源:flicker.go
示例14: send
func send(ws *websocket.Conn, path string, evs <-chan store.Event) {
l := len(path) - 1
for ev := range evs {
ev.Getter = nil // don't marshal the entire snapshot
ev.Path = ev.Path[l:]
b, err := json.Marshal(ev)
if err != nil {
log.Println(err)
return
}
_, err = ws.Write(b)
if err != nil {
log.Println(err)
return
}
}
}
开发者ID:Br3nda,项目名称:doozerd,代码行数:17,代码来源:web.go
示例15: socketHandler
func socketHandler(c *websocket.Conn) {
in, out := make(chan *Message), make(chan *Message)
errc := make(chan error, 1)
// Decode messages from client and send to the in channel.
go func() {
dec := json.NewDecoder(c)
for {
var m Message
if err := dec.Decode(&m); err != nil {
errc <- err
return
}
in <- &m
}
}()
// Receive messages from the out channel and encode to the client.
go func() {
enc := json.NewEncoder(c)
for m := range out {
if err := enc.Encode(m); err != nil {
errc <- err
return
}
}
}()
// open a connection to minimega and handle the request
megaconns := make(map[string]*megaconn)
for {
select {
case m := <-in:
log.Debugln("running snippet from:", c.Request().RemoteAddr)
lOut := limiter(in, out)
megaconns[m.Id] = runMega(m.Id, m.Body, lOut)
case err := <-errc:
if err != io.EOF {
// A encode or decode has failed; bail.
log.Errorln(err)
}
return
}
}
}
开发者ID:npe9,项目名称:minimega,代码行数:45,代码来源:socket.go
示例16: WebSocketServer
func WebSocketServer(ws *websocket.Conn) {
fmt.Println("WebSocketServer")
var msg [1024]byte
ch := CreateReadChannel(ws, msg[:])
interval := time.Tick(5 * 1e9)
Loop:
for {
select {
case n := <-ch:
if n == 0 {
fmt.Println("The connection was closed by peer.")
break Loop
}
ws.Write(msg[:n])
case _ = <-interval:
ws.Write([]byte("An interval event fired in a server side."))
}
}
}
开发者ID:Saikees,项目名称:practice,代码行数:19,代码来源:websocket.go
示例17: indexHandler
func indexHandler(ws *websocket.Conn) {
var ibuff [50]byte
i, err := ws.Read(ibuff[0:50])
if err != nil {
fmt.Printf("WebSocket error: " + err.String())
return
}
msg := string(ibuff[0:i])
idx := strings.Index(msg, "!")
if idx < 0 {
fmt.Printf("Salt not found\n")
return
}
idstr := msg[0:idx]
salt := msg[idx+1:]
uid, err := strconv.Atoui64(idstr)
if err != nil {
fmt.Printf("User ID invalid\n")
return
}
defer UnlinkUser(uid, ws)
usr := LinkUser(uid, salt, ws)
if usr == nil {
fmt.Printf("Cannot link with User ID\n")
return
}
for usr.exit == false {
time.Sleep(1e8)
if IsClosed(ws) {
break
}
}
}
开发者ID:hpcorona,项目名称:webtalk,代码行数:41,代码来源:main.go
示例18: 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())
}
开发者ID:mesutcan,项目名称:gogaruco2011,代码行数:21,代码来源:web_tcat.go
示例19: 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.")
}
}
}
}
}
开发者ID:klinster,项目名称:Bessie,代码行数:40,代码来源:websockets.go
示例20: 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],
}
}
}
开发者ID:natelong,项目名称:playlistr,代码行数:23,代码来源:playlistr.go
注:本文中的websocket.Conn类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论