本文整理汇总了Golang中golang.org/x/net/websocket.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
for i := 0; i < 2000; i++ {
go func(num int) {
t := time.Now().UnixNano()
ws, err := websocket.Dial("wss://ws.binaryws.com/websockets/v3?app_id=1&l=EN", "", "http://load_test")
chk(err)
fmt.Println("Time", num, ":", float64(time.Now().UnixNano()-t)/1000000000)
for j := 0; j < 3000; j++ {
t = time.Now().UnixNano()
_, err = ws.Write([]byte(req))
chk(err)
var msg = make([]byte, 5120)
_, err := ws.Read(msg)
chk(err)
// fmt.Println(string(msg))
if j%10 == 0 {
ws, _ = websocket.Dial("wss://ws.binaryws.com/websockets/v3?app_id=1&l=EN", "", "http://load_test")
fmt.Printf("[%d, %d] Received for : %d after %f\n", j, num, num, float64(time.Now().UnixNano()-t)/1000000000)
}
time.Sleep(time.Millisecond * 1100)
}
}(i)
}
time.Sleep(time.Second * 10000)
}
示例2: TestAddClientRecive
func TestAddClientRecive(t *testing.T) {
var server = GlobalIM
var roomID = "master"
server.Init()
t.Log("add a room")
server.Rm.Add(roomID)
go func() {
if err := http.ListenAndServe("localhost:9999", nil); err != nil {
panic(err)
}
}()
// let listen start.
time.Sleep(2 * time.Second)
ws1, err := websocket.Dial("ws://localhost:9999/im?room_id="+roomID+"&uname=1", "", "http://localhost:9999")
if err != nil {
t.Fatal(err)
}
ws2, err := websocket.Dial("ws://localhost:9999/im?room_id="+roomID+"&uname=2", "", "http://localhost:9999")
if err != nil {
t.Fatal(err)
}
ws3, err := websocket.Dial("ws://localhost:9999/im?room_id="+roomID+"&uname=3", "", "http://localhost:9999")
if err != nil {
t.Fatal(err)
}
m := &msg{
Playload: "client1",
}
t.Log("will send.")
if err := websocket.JSON.Send(ws1, m); err != nil {
t.Fatal(err)
} else {
t.Log("has been send.")
}
m = new(msg)
if err := websocket.JSON.Receive(ws2, m); err != nil {
t.Fatal(err)
}
t.Log("Get message:", string(m.Playload))
if err := websocket.JSON.Receive(ws3, m); err != nil {
t.Fatal(err)
}
t.Log("Get message:", string(m.Playload))
data, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
t.Log("Json", string(data))
}
示例3: Forever
func (this *Client) Forever(pattern string, route bool) (chan *jarvis.Event, error) {
var process string
if route {
process = this.Process
}
ws, err := websocket.Dial("ws://"+this.Root+"/subscribe/forever?process="+process+"&pattern="+pattern, "", "http://jarvis")
if err != nil {
log.Println(err)
return nil, err
}
result := make(chan *jarvis.Event)
go func() {
msg := make([]byte, 4096)
for {
n, err := ws.Read(msg)
if err != nil {
break
}
event := new(jarvis.Event)
err = json.Unmarshal(msg[:n], &event)
result <- event
}
close(result)
}()
return result, nil
}
示例4: connect
func connect(userID string, clientID string) {
ws, err := websocket.Dial(getServer(), "", "http://localhost/")
if err != nil {
Debug(err.Error())
return
}
message := []byte(fmt.Sprintf("%s:%s", userID, clientID))
_, err = ws.Write(message)
if err != nil {
Debug(err.Error())
return
}
Debug(fmt.Sprintf("Sent: %s\n", message))
for {
var msg = make([]byte, 512)
_, err = ws.Read(msg)
if err != nil {
Debug(err.Error())
return
}
Debug(fmt.Sprintf("Received: %s\n", msg))
CmdChan <- string(bytes.Trim(msg, "\x00"))
}
}
示例5: TestEchoWithoutTestHelpers
func TestEchoWithoutTestHelpers(t *testing.T) {
s := neptulon.NewServer("127.0.0.1:3002")
go s.ListenAndServe()
time.Sleep(time.Millisecond * 30)
defer s.Close()
s.MiddlewareFunc(func(ctx *neptulon.ReqCtx) error {
t.Log("Request received:", ctx.Method)
ctx.Res = "response-wow!"
return ctx.Next()
})
origin := "http://127.0.0.1"
url := "ws://127.0.0.1:3002"
ws, err := websocket.Dial(url, "", origin)
if err != nil {
t.Fatal(err)
}
if err := websocket.JSON.Send(ws, map[string]string{"id": "123", "method": "test"}); err != nil {
t.Fatal(err)
}
var res interface{}
if err := websocket.JSON.Receive(ws, &res); err != nil {
t.Fatal(err)
}
t.Log("Got response:", res)
if err := ws.Close(); err != nil {
t.Fatal(err)
}
time.Sleep(time.Millisecond * 30)
}
示例6: TestProxyUpgrade
func TestProxyUpgrade(t *testing.T) {
backendServer := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
body := make([]byte, 5)
ws.Read(body)
ws.Write([]byte("hello " + string(body)))
}))
defer backendServer.Close()
serverURL, _ := url.Parse(backendServer.URL)
proxyHandler := &UpgradeAwareProxyHandler{
Location: serverURL,
}
proxy := httptest.NewServer(proxyHandler)
defer proxy.Close()
ws, err := websocket.Dial("ws://"+proxy.Listener.Addr().String()+"/some/path", "", "http://127.0.0.1/")
if err != nil {
t.Fatalf("websocket dial err: %s", err)
}
defer ws.Close()
if _, err := ws.Write([]byte("world")); err != nil {
t.Fatalf("write err: %s", err)
}
response := make([]byte, 20)
n, err := ws.Read(response)
if err != nil {
t.Fatalf("read err: %s", err)
}
if e, a := "hello world", string(response[0:n]); e != a {
t.Fatalf("expected '%#v', got '%#v'", e, a)
}
}
示例7: Start
func (c Client) Start() error {
ws, err := websocket.Dial(c.url(), "", c.originUrl())
if err != nil {
return err
}
chat := chat_sample_view.NewChatView("CHAT>")
chat.EnterAction = func(text string) {
msg := Message{Name: c.Name, Text: text}
data, _ := json.Marshal(msg)
ws.Write(data)
}
chat.Init()
defer chat.Close()
go func() {
for {
rcv := make([]byte, 512)
n, _ := ws.Read(rcv)
var msg Message
json.Unmarshal(rcv[0:n], &msg)
chat.Message(&msg)
}
}()
chat.Draw()
chat.PollInput()
return nil
}
示例8: Connect
// Connect trys to connect the bot to the slack channel via token. It also stores the initial state of the slack.
func (b *Bot) Connect(token string) error {
c := &http.Client{}
resp, err := c.Get("https://slack.com/api/rtm.start?token=" + token)
if err != nil {
return err
}
dec := json.NewDecoder(resp.Body)
var val rtmStart
if err := dec.Decode(&val); err != nil {
return err
}
resp.Body.Close()
u, err := url.Parse(val.URL)
if err != nil {
return err
}
u.Host += ":443"
conn, err := websocket.Dial(u.String(), "", "https://slack.com")
if err != nil {
return err
}
b.Channels = val.Channels
b.Conn = conn
b.Users = val.Users
b.Self = val.Self
b.Team = val.Team
return nil
}
示例9: TestWebSocket_Query
func TestWebSocket_Query(t *testing.T) {
mux := http.NewServeMux()
h := Handler{Tx: newTransceiver()}
<-h.Register(mux)
s := httptest.NewServer(mux)
defer s.Close()
url := strings.Replace(s.URL, "http:", "ws:", 1)
ws, err := websocket.Dial(url+"/v1/ws/jsonrpc", "", "http://localhost")
if err != nil {
t.Fatal(err)
}
defer ws.Close()
cli := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(ws))
args := &QueryMessage{
Src: "nobody",
MessageID: "foobar",
}
var resp QueryMessageResp
err = cli.Call("SM.Query", args, &resp)
if err != nil {
t.Fatal(err)
}
want := "DELIVERED"
if resp.MsgState != want {
t.Fatalf("unexpected message state: want %q, have %q",
want, resp.MsgState)
}
}
示例10: newWSProxy
// newWSProxy returns a websocket handler which forwards
// messages from an incoming WS connection to an outgoing
// WS connection. It builds upon the golang.org/x/net/websocket
// library for both incoming and outgoing connections.
func newWSProxy(t *url.URL) http.Handler {
return websocket.Handler(func(in *websocket.Conn) {
defer in.Close()
r := in.Request()
targetURL := "ws://" + t.Host + r.RequestURI
out, err := websocket.Dial(targetURL, "", r.Header.Get("Origin"))
if err != nil {
log.Printf("[INFO] WS error for %s. %s", r.URL, err)
return
}
defer out.Close()
errc := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
errc <- err
}
go cp(out, in)
go cp(in, out)
err = <-errc
if err != nil && err != io.EOF {
log.Printf("[INFO] WS error for %s. %s", r.URL, err)
}
})
}
示例11: Connect
func (m *MatlabSession) Connect() {
origin := "http://localhost/"
url := "ws://localhost:9999/matsock"
// url = "ws://localhost:12345/echo"
var err error
m.matlabshell, err = websocket.Dial(url, "", origin)
if err != nil {
log.Fatal(err)
}
// Say hello to the matlab shell
// n, err := m.matlabshell.Write([]byte("Matlab Connecting... !"))
// log.Printf("Wrote %d writing Error %v ", n, err)
// var msg = make([]byte, 512)
// if n, err = m.matlabshell.Read(msg); err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Received: %s.\n", msg[:n])
// var msg = make([]byte, 512)
// var n int
// if n, err = ws.Read(msg); err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Received: %s.\n", msg[:n])
// m.matlabshell=
}
示例12: main
func main() {
var url, origin string
flag.StringVar(&url, "url", "ws://127.0.0.1:9999/echo", "websocket URL")
flag.StringVar(&origin, "origin", "http://localhost/", "origin header")
flag.Parse()
if url == "" {
flag.Usage()
os.Exit(1)
}
ws, err := websocket.Dial(url, "", origin)
if err != nil {
log.Fatal(err)
}
go func() {
var msg = make([]byte, 512)
for {
n, err := ws.Read(msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("R: %s\nS: ", msg[:n])
}
}()
fmt.Print("S: ")
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
if _, err := ws.Write(sc.Bytes()); err != nil {
log.Fatal(err)
}
}
}
示例13: connect
// connect logs on user. Blocks until successfull and
// returns the websocket connection
func connect(hostWS, username string, client int) (conn *websocket.Conn) {
// Request Mycel server to log in
for {
var err error
conn, err = websocket.Dial(fmt.Sprintf("%s/subscribe/clients/%d", hostWS, client), "", "http://localhost")
if err != nil {
fmt.Println("Can't connect to Mycel websocket server. Trying reconnect in 1 second...")
time.Sleep(1 * time.Second)
continue
}
break
}
// Create and send log-on request
logonMsg := logOnOffMessage{Action: "log-on", Client: client, User: username}
err := websocket.JSON.Send(conn, logonMsg)
if err != nil {
fmt.Println("Couldn't send message " + err.Error())
}
// Wait for "logged-on" confirmation
var msg message
for {
err := websocket.JSON.Receive(conn, &msg)
if err != nil {
if err == io.EOF {
break
}
fmt.Println("Couldn't receive msg " + err.Error())
}
if msg.Status == "logged-on" {
break
}
}
return
}
示例14: newWSConnection
func (conn *Connection) newWSConnection() (*websocket.Conn, error) {
resp, err := http.PostForm(
"https://slack.com/api/rtm.start",
url.Values{"token": {conn.token}},
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var r RTMStart
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, err
}
conn.userId = r.Self.Id
conn.userName = r.Self.Name
conn.domain = r.Team.Domain
conn.userMap = map[string]string{}
conn.channelMap = map[string]string{}
for _, v := range r.Users {
conn.userMap[v.Id] = v.Name
}
for _, v := range r.Channels {
conn.channelMap[v.Id] = v.Name
}
return websocket.Dial(r.Url, "", "https://slack.com/")
}
示例15: reconnect
func reconnect(origin, deviceId, channelId, endpoint string) (err error) {
socket, err := ws.Dial(origin, "", origin)
if err != nil {
return fmt.Errorf("Error dialing origin: %s", err)
}
connId, err := id.Generate()
if err != nil {
return fmt.Errorf("Error generating connection ID: %#v", err)
}
conn := client.NewConn(socket, connId, true)
defer conn.Close()
defer conn.Purge()
actualId, err := conn.WriteHelo(deviceId, channelId)
if err != nil {
return fmt.Errorf("Error writing handshake request: %s", err)
}
if actualId != deviceId {
return fmt.Errorf("Mismatched device IDs: got %q; want %q",
actualId, deviceId)
}
if err = roundTrip(conn, deviceId, channelId, endpoint, 2); err != nil {
return fmt.Errorf("Error sending notification after reconnect: %s", err)
}
return nil
}