本文整理汇总了Golang中golang.org/x/net/websocket.Conn.RemoteAddr方法的典型用法代码示例。如果您正苦于以下问题:Golang Conn.RemoteAddr方法的具体用法?Golang Conn.RemoteAddr怎么用?Golang Conn.RemoteAddr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/net/websocket.Conn
的用法示例。
在下文中一共展示了Conn.RemoteAddr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: BuildConnection
func BuildConnection(ws *websocket.Conn) {
log.Info("BuildConnection()")
token := ws.Request().URL.Query().Get("token")
log.Debug(token)
var uci userConnectionInfo
err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("validation error")
// how should this reply to the client?
return
}
onlineUser := &OnlineUser{
Connection: ws,
Uci: uci,
Send: make(chan envelope, 256),
}
runningRoom.Users[onlineUser] = true
go onlineUser.PushToClient()
onlineUser.PullFromClient()
delete(runningRoom.Users, onlineUser)
log.Info("tore down user connection")
}
示例2: 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()
}()
}
示例3: socketListener
func socketListener(ws *websocket.Conn) {
for {
log.Printf("Connection Opened from %v", ws.RemoteAddr())
activePlotter = ws
cnt := 0
for {
in := bufio.NewReader(os.Stdin)
fmt.Printf("WebPlot > ")
str, _ := in.ReadString('\n')
var plotcmd PlotInfo
// log.Println("Input Command ", str)
str = strings.TrimSpace(str)
if strings.Contains(str, "SIN") {
log.Printf("YOU ARE IN ", str)
plotcmd.Type = "plot"
plotcmd.HoldOn = (str == "SINH")
plotcmd.Handle = 120
plotcmd.Y = vlib.RandNFVec(100, 1)
plotcmd.Options.Color = "red"
plotcmd.Options.Title = fmt.Sprintf("Figure %d - (%d)", plotcmd.Handle, cnt)
cnt++
log.Println(plotcmd.Y)
data, err := json.Marshal(plotcmd)
if err != nil {
log.Println("Err is ", err)
break
}
activePlotter.Write(data)
}
if str == "COS" {
plotcmd.Type = "plot"
plotcmd.HoldOn = true
plotcmd.Handle = rand.Intn(100)
plotcmd.Y = vlib.RandNFVec(100, 1)
plotcmd.Options.Color = "red"
plotcmd.Options.Title = fmt.Sprintf("Figure %d", cnt)
cnt++
log.Println(plotcmd.Y)
data, err := json.Marshal(plotcmd)
if err != nil {
log.Println("Err is ", err)
break
}
activePlotter.Write(data)
}
}
}
}
示例4: serveWebsocket
func serveWebsocket(conn *websocket.Conn) {
var (
// ip addr
lAddr = conn.LocalAddr()
rAddr = conn.RemoteAddr()
// timer
tr = DefaultServer.round.Timer(rand.Int())
)
log.Debug("start websocket serve \"%s\" with \"%s\"", lAddr, rAddr)
DefaultServer.serveWebsocket(conn, tr)
}
示例5: wslogsHandler
func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) {
source := w.Request().FormValue("source")
host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano())
defer func() {
log.Printf("[%s - %s] closing websocket conn", ws.name, w.RemoteAddr().String())
ws.b.DelSubscriber(host)
w.Close()
}()
log.Printf("[%s - %s] accepting websocket conn", ws.name, w.RemoteAddr().String())
r := make(chan *buffer.Event, recvBuffer)
ws.b.AddSubscriber(host, r)
for {
select {
case ev := <-r:
if len(source) > 0 {
if ev.Source != source {
continue
}
}
err := websocket.Message.Send(w, *ev.Text)
if err != nil {
log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error())
return
}
}
}
}
示例6: wsConnHandler
// wsHandler handles incoming websocket connections.
func (s *Server) wsConnHandler(ws *websocket.Conn) {
c, err := NewConn()
if err != nil {
log.Printf("server: error while accepting connection: %v", err)
return
}
defer recoverAndLog(c, &s.wg)
c.MiddlewareFunc(s.middleware...)
log.Printf("server: client connected %v: %v", c.ID, ws.RemoteAddr())
s.conns.Set(c.ID, c)
c.setConn(ws)
c.startReceive()
s.conns.Delete(c.ID)
s.disconnHandler(c)
}
示例7: handleMatlabCommands
// Handles commands comming from Matlab Session objects and writes to the corresponding
func handleMatlabCommands(ms *websocket.Conn) {
log.Printf("New Mat Client %s", ms.RemoteAddr())
io.Copy(activePlotter, ms)
// for {
// var msg []byte
// msg = make([]byte, 1024)
// // log.Printf("Trying to read..")
// n, err := ms.Read(msg)
// _ = err
// if n > 0 {
// log.Printf("WSServer Rx: %s", msg[0:n])
// activePlotter.Write(msg)
// }
// }
log.Println("Leaving session")
}
示例8: HandlerChat
// HandlerChat is called in a goroutine for every connection the websocket accepts.
func HandlerChat(conn *websocket.Conn) {
defer log.Printf("Closing websocket connection")
log.Printf("New websocket connection")
// reuse buffers; keep memory usage low!
// TODO: Look into reusing memory buffers
buff := make([]byte, 1024)
var event Event
me := new(User)
me.conn = conn
me.Remote = conn.RemoteAddr().String()
loop:
for {
n, err := conn.Read(buff)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
log.Printf("[chat] EOF\n")
conn.Close()
break loop
}
GlobalServer.Errors <- err
}
log.Printf("Got: '%v'", string(buff[:n]))
if err := json.Unmarshal(buff[:n], &event); err != nil {
GlobalServer.Errors <- err
}
switch event.Type {
case EVENT_NEWTOPIC:
me.HandleNewTopic(event)
case EVENT_MESSAGE:
me.HandleMessage(event)
case EVENT_LEAVE:
me.HandleLeave(event)
case EVENT_LOGIN:
me.HandleLogin(event)
case EVENT_VOTE:
me.HandleVote(event)
default:
log.Printf("Unhanlded event type in user handler")
}
}
}
示例9: ChatServer
func ChatServer(ws *websocket.Conn) {
lenBuf := make([]byte, 5)
msgChan := make(chan *Msg, 100)
clientKey := ws.RemoteAddr().String()
clientRequests <- &NewClientEvent{clientKey, msgChan}
defer func() { clientDisconnects <- clientKey }()
go func() {
for msg := range msgChan {
ws.Write([]byte(msg.text))
}
}()
for {
_, err := ws.Read(lenBuf)
if err != nil {
log.Println("Error: ", err.Error())
return
}
length, _ := strconv.Atoi(strings.TrimSpace(string(lenBuf)))
if length > 65536 {
log.Println("Error: too big length: ", length)
return
}
if length <= 0 {
log.Println("Empty length")
return
}
buf := make([]byte, length)
_, err = ws.Read(buf)
if err != nil {
log.Println("Could not read", length)
return
}
messages <- &Msg{clientKey, string(buf)}
}
}
示例10: BuildConnection
func BuildConnection(ws *websocket.Conn) {
token := ws.Request().URL.Query().Get("token")
fmt.Println(token)
var uci userConnectionInfo
err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci)
if err != nil {
fmt.Println("validation error: " + err.Error())
// how should this reply to the client?
return
}
onlineUser := &OnlineUser{
Connection: ws,
Uci: uci,
Send: make(chan envelope, 256),
}
runningRoom.Users[onlineUser] = true
go onlineUser.PushToClient()
onlineUser.PullFromClient()
delete(runningRoom.Users, onlineUser)
}
示例11: WebHandler
// Handles all Websocket connections
func WebHandler(ws *websocket.Conn) {
log.Printf("WebHandler: New connection from %v", ws.RemoteAddr())
// Create a new connection structure
c := NewConnection(ws)
// Notify hub to register the new connection
DefaultHub.Register <- c
// Defer the hub notification to unregister when this connection is closed
defer func() {
log.Printf("WebHandler: deferred call to remove connection from registry %v", ws.RemoteAddr())
DefaultHub.Unregister <- c
}()
// Start writing in a separate goroutine
go c.Writer()
// Start reading from socket in the current goroutine
c.Reader()
}
示例12: Handle
func (c *WSClientHandler) Handle(ws *websocket.Conn) {
if core.Closing {
ws.Close()
return
}
rwc := NewWSConn(ws)
id := core.clientList.Add(rwc, ws.RemoteAddr().String())
mailbox := rpc.NewMailBox(1, id, core.AppId)
core.Emitter.Push(NEWUSERCONN, map[string]interface{}{"id": id}, true)
cl := core.clientList.FindNode(id)
cl.MailBox = mailbox
cl.Run()
codec := &ClientCodec{}
codec.rwc = rwc
codec.cachebuf = make([]byte, SENDBUFLEN)
codec.node = cl
log.LogInfo("new client:", mailbox, ",", ws.RemoteAddr())
core.rpcServer.ServeCodec(codec, rpc.MAX_BUF_LEN)
core.Emitter.Push(LOSTUSERCONN, map[string]interface{}{"id": cl.Session}, true)
log.LogMessage("client handle quit")
}
示例13: wsACMASites
func wsACMASites(ws *websocket.Conn) {
c := &ClientConn{}
c.ws = ws
c.cmd = make(chan uint8)
var cmd uint8
log.Println("New wsACMASites Conection: ", ws.RemoteAddr())
newConn <- c
clients.Lock()
clients.Clients++
clients.Unlock()
for {
// read the packet
// TODO: Reduce allocations
packet := c.inBuffer[0:]
n, err := ws.Read(packet)
packet = packet[0:n]
if err != nil {
log.Println("wsACMASites Read Error: ", err)
clients.Lock()
clients.Clients--
clients.Unlock()
break
}
buf := bytes.NewBuffer(packet)
// its all binary
err = binary.Read(buf, binary.LittleEndian, &cmd)
if err != nil {
log.Println(err)
clients.Lock()
clients.Clients--
clients.Unlock()
break
}
// Hope this works like I think it will
c.cmd <- cmd
}
}
示例14: WSServe
func WSServe(sess session.Session, conn *websocket.Conn) {
logger.Printf("session ip[%s] start serve\n", conn.RemoteAddr().String())
sess.OnOpen()
for {
var tempContent []byte
if err := websocket.Message.Receive(conn, &tempContent); err != nil {
if err != io.EOF {
logger.Printf("session ip[%s] handle data error[%s]", conn.RemoteAddr().String(), err.Error())
sess.OnError(err)
err = sess.Close()
if err != nil {
logger.Printf("session ip[%s] close error[%s]", conn.RemoteAddr().String(), err.Error())
}
} else {
logger.Printf("remote ip [%s] active close\n", conn.RemoteAddr().String())
sess.OnClose()
}
break
}
logger.Printf("receive data from %s,data [%v]\n", conn.RemoteAddr().String(), tempContent)
sess.OnReceive(tempContent)
}
}
示例15: makeWebsocketName
// makeWebsocketName composes an identifier for a websocket client
func makeWebsocketName(ws *websocket.Conn) string {
return fmt.Sprintf("[%p]%s", ws, ws.RemoteAddr())
}