R
R
Roman Rakzin2015-03-31 17:24:48
go
Roman Rakzin, 2015-03-31 17:24:48

How to send data to a specific socket?

Good afternoon. How to send data to specific socket
using code.google.com/p/go.net/websocket ?
There are 2 files:

main.go
       package main

    import (
        "code.google.com/p/go.net/websocket"
        "html/template"
        "log"
        "net/http"
        "os"
    )

    const (
        listenAddr = "localhost:4000" // server address
    )

    var (
        pwd, _        = os.Getwd()
        RootTemp      = template.Must(template.ParseFiles(pwd + "/chat.html"))
        JSON          = websocket.JSON           // codec for JSON
        Message       = websocket.Message        // codec for string, []byte
        ActiveClients = make(map[ClientConn]int) // map containing clients
    )

    func init() {
        http.HandleFunc("/", RootHandler)
        http.Handle("/sock", websocket.Handler(SockServer))
    }

    type ClientConn struct {
        websocket *websocket.Conn
        clientIP  string
    }

    func SockServer(ws *websocket.Conn) {
        var err error
        var clientMessage string

        defer func() {
            if err = ws.Close(); err != nil {
                log.Println("Websocket could not be closed", err.Error())
            }
        }()

        client := ws.Request().RemoteAddr
        log.Println("Клиент подключился:", client)
        sockCli := ClientConn{ws, client}
        ActiveClients[sockCli] = 0
        log.Println("Количество клиентов ...", len(ActiveClients))

        // for loop so the websocket stays open otherwise
        // it'll close after one Receieve and Send
        for {
            if err = Message.Receive(ws, &clientMessage); err != nil {
                // If we cannot Read then the connection is closed
                log.Println("Клиент отключился", err.Error())
                // remove the ws client conn from our active clients
                delete(ActiveClients, sockCli)
                log.Println("Количество подключений ...", len(ActiveClients))
                return
            }

            clientMessage = sockCli.clientIP + " сказал: " + clientMessage
            log.Println(sockCli.clientIP + " сказал--->: " + clientMessage)

            //Message.Send(ActiveClients[1].websocket, 'Это сообщение тебе')
            for cs, _ := range ActiveClients {
                Message.Send(cs.websocket, 'Testtt')
                if err = Message.Send(cs.websocket, clientMessage); err != nil {
                    log.Println("Could not send message to ", cs.clientIP, err.Error())
                }



            }
        }
    }

    func RootHandler(w http.ResponseWriter, req *http.Request) {
        err := RootTemp.Execute(w, listenAddr)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    }

    func main() {
        err := http.ListenAndServe(listenAddr, nil)
        if err != nil {
            panic("ListenAndServe: " + err.Error())
        }
    }

------------------Chat.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title> WebSockets </title>
        <style>
            * {
                padding: 0px;
                margin: 0px;
            }
            body {
                width:100%;
                font-family: fantasy;
                font-size: 13px;
            }
            h1 {
                text-align: center;
            }
            #text {
                position: relative;
                left: 500px;
                top: 20px;
            }
            #chat-box-container {
                width: 600px;
                height: 100%;
                position: relative;
                left: 500px;
                top: 50px;
            }
            #chatbox {
                position: relative;
                right: 150px;
                border-style: solid;
                border-radius: 2px;
                padding: 10px;
            }
        </style>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script>
            try {
                var sock = new WebSocket("ws://{{.}}/sock");
                //sock.binaryType = 'blob'; // can set it to 'blob' or 'arraybuffer 
                console.log("Websocket - status: " + sock.readyState);
                sock.onopen = function(m) { 
                    console.log("CONNECTION opened..." + this.readyState);}
                sock.onmessage = function(m) { 
                    $('#chatbox').append('<p>' + m.data + '</p>');}
                sock.onerror = function(m) {
                    console.log("Error occured sending..." + m.data);}
                sock.onclose = function(m) { 
                    console.log("Disconnected - status " + this.readyState);}
            } catch(exception) {
                console.log(exception);
            }
        </script>
    </head>
    <body>
        <h1> This chat is powered by web sockets </h1>
        <div id ="text">
        <textarea id="textin" cols="30" rows="4" placeholder="This is where you type..." autofocus>
        </textarea>
        <button id="send">Send Message</button>
        </div>

        <div id="chat-box-container">
            <h2> This is the chatbox... </h2>
            <div id="chatbox">
                <p> Go Type stuff... </p>
            </div>
        </div>

        <script>
            $('#textin').val("");
            // take what's the textbox and send it off
            $('#send').click( function(event) {
                sock.send($('#textin').val());
                $('#textin').val("");
            });
        </script>
    </body>
</html>

But here the data is sent to everyone.
How to send data to a specific socket?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2015-03-31
@uvelichitel

Data is sent to everyone in a loop

for cs, _ := range ActiveClients {
                Message.Send(cs.websocket, 'Testtt')
                if err = Message.Send(cs.websocket, clientMessage); err != nil {
                    log.Println("Could not send message to ", cs.clientIP, err.Error())
                }
}

send data to a specific clientIP (let's say 127.0.0.1) like this
for cs, _ := range ActiveClients {
         if cs.clientIP ==  "127.0.0.1"{
                Message.Send(cs.websocket, 'Testtt')
                if err = Message.Send(cs.websocket, clientMessage); err != nil {
                    log.Println("Could not send message to ", cs.clientIP, err.Error())
                }
         }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question