go get golang.org/x/net/websocket
package main;
import (
"golang.org/x/net/websocket"
"net/http"
"log"
"fmt"
)
//使用golang.org/x/net/websocket
//如果无法下载,请到下面的地址去下载
//http://www.golangtc.com/download/package
//http://gopm.io/
type Msg struct {
From string;
To string;
Data string;
}
//处理简单的字符串
func test(conn *websocket.Conn) {
var err error;
for {
data := "";
//接收消息
err = websocket.Message.Receive(conn, &data);
if err != nil {
break;
}
fmt.Println("client send: " + data);
msg := "hello " + data;
//发送消息
err = websocket.Message.Send(conn, msg);
if err != nil {
break;
}
}
}
//处理JSON数据
func test2(conn *websocket.Conn) {
var err error;
for {
var data Msg;
//接收消息
err = websocket.JSON.Receive(conn, &data);
if err != nil {
break;
}
fmt.Println(data.From, data.To, data.Data);
msg := Msg{
From: data.From,
To: data.To,
Data: "hello " + data.Data,
};
//发送消息
err = websocket.JSON.Send(conn, msg);
if err != nil {
break;
}
}
}
func main() {
//http.Handle("/", websocket.Handler(test));
http.Handle("/", websocket.Handler(test2));
err := http.ListenAndServe(":8080", nil);
if err != nil {
log.Fatal(err);
}
}