Как отослать данные определённому сокету?

Добрый день. Как отправить данные на определённые сокет,
используя code.google.com/p/go.net/websocket ?

Есть 2 файла:

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>


Но здесь данные отправляются всем.
Как отослать данные определённому сокету?
Спасибо
  • Вопрос задан
  • 250 просмотров
Пригласить эксперта
Ответы на вопрос 1
uvelichitel
@uvelichitel Куратор тега Go
habrahabr.ru/users/uvelichitel
Данные отправляются всем в цикле
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())
                }
}

отправить данные на определённый clientIP (пусть 127.0.0.1) например так
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())
                }
         }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы