本文整理匯總了Golang中code/google/com/p/go/net/websocket.Conn.Write方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.Write方法的具體用法?Golang Conn.Write怎麽用?Golang Conn.Write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類code/google/com/p/go/net/websocket.Conn
的用法示例。
在下文中一共展示了Conn.Write方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: docServer
func docServer(ws *websocket.Conn) {
for {
in := make([]byte, 512)
n, err := ws.Read(in)
if err != nil {
fmt.Println(err)
break
}
fmt.Println(string(in[:n]))
msg := &Message{}
json.Unmarshal(in[:n], &msg)
switch msg.DocType {
case "req":
response := &DocumentMessage{DocType: "doc", Version: doc.Version, Content: doc.Content}
json, _ := json.Marshal(response)
ws.Write(json)
case "edit":
editMsg := &EditMessage{}
json.Unmarshal(in[:n], &editMsg)
doc.RemoteVersion = editMsg.Edits[len(editMsg.Edits)-1].Version
response := &AckMessage{DocType: "ack", Version: doc.RemoteVersion}
json, _ := json.Marshal(response)
ws.Write(json)
}
}
}
示例2: HandleAPI
func (endpoint *WebsocketEndpoint) HandleAPI(
buf []byte, session Session, ws *websocket.Conn) {
var data APIData
var resolver = msgpack.DefaultDecoderContainerResolver
resolver.MapType = reflect.TypeOf(make(APIData))
var dec = msgpack.NewDecoder(bytes.NewReader(buf), &resolver)
var err = dec.Decode(&data)
if err != nil {
fmt.Printf("Decode err: %v\n", err)
return
}
var response = endpoint.context.API().HandleRequest(
data, session, endpoint.context)
if id, ok := data["id"]; ok {
response["id"] = id
}
w := bytes.NewBufferString("")
w.WriteByte('a')
enc := msgpack.NewEncoder(w)
err = enc.Encode(response)
if err != nil {
fmt.Printf("Encode err: %#v\n", err)
return
}
ws.Write(w.Bytes())
}
示例3: handle
func (fh *FakeHandler) handle(conn *websocket.Conn) {
fh.call()
request := conn.Request()
fh.setLastURL(request.URL.String())
fh.setAuthHeader(request.Header.Get("Authorization"))
if fh.messageReceived != nil {
go func() {
for {
buffer := make([]byte, 1024)
_, err := conn.Read(buffer)
if err == nil {
fh.messageReceived <- true
} else {
break
}
}
}()
}
for _, protoMessage := range fh.Messages {
if protoMessage == nil {
conn.Write([]byte{})
} else {
message, err := proto.Marshal(protoMessage)
Expect(err).ToNot(HaveOccurred())
conn.Write(message)
}
}
<-fh.closeConnection
conn.Close()
}
示例4: FrameServer
// Write received messages from a channel to the websocket client
func FrameServer(conn *websocket.Conn) {
// Set the PayloadType to binary
conn.PayloadType = websocket.BinaryFrame
client := NewClient()
registerClient <- client
defer func() {
unregisterClient <- client
}()
// Write the header as the first message to the client (MPEG size etc.)
conn.SetWriteDeadline(time.Now().Add(ClientWriteTimeout * time.Second))
if _, err := conn.Write(*headerMessage); err != nil {
return
}
// Continuously read messages from the queue and write to the client, stop on error
for msg := range client.queue {
conn.SetWriteDeadline(time.Now().Add(ClientWriteTimeout * time.Second))
if _, err := conn.Write(*msg); err != nil {
return
}
}
}
示例5: syscallHandler
func syscallHandler(conn *websocket.Conn) {
reader := bufio.NewReader(conn)
decoder := json.NewDecoder(reader)
for {
var command map[string]interface{}
if err := decoder.Decode(&command); err == io.EOF {
break
} else if err != nil {
log.Println("Decoder error", err)
continue
}
if response, err := handleSyscall(conn, command); err != nil {
log.Println(err)
continue
} else {
if _, err := conn.Write(response); err != nil {
log.Println(err)
continue
}
}
}
}
示例6: redirToWs
func redirToWs(fd int, ws *websocket.Conn) {
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "Error occured: %s\n", r)
runtime.Goexit()
}
}()
var buf [8192]byte
start, end, buflen := 0, 0, 0
for {
switch nr, er := syscall.Read(fd, buf[start:]); {
case nr < 0:
fmt.Fprintf(os.Stderr, "error reading from websocket %d with code %d\n", fd, er)
return
case nr == 0: // EOF
return
case nr > 0:
buflen = start + nr
for end = buflen - 1; end >= 0; end-- {
if utf8.RuneStart(buf[end]) {
ch, width := utf8.DecodeRune(buf[end:buflen])
if ch != utf8.RuneError {
end += width
}
break
}
if buflen-end >= 6 {
fmt.Fprintf(os.Stderr, "Invalid UTF-8 sequence in output")
end = nr
break
}
}
runes := bytes.Runes(buf[0:end])
buf_clean := []byte(string(runes))
nw, ew := ws.Write(buf_clean[:])
if ew != nil {
fmt.Fprintf(os.Stderr, "error writing to websocket with code %s\n", ew)
return
}
if nw != len(buf_clean) {
fmt.Fprintf(os.Stderr, "Written %d instead of expected %d\n", nw, end)
}
start = buflen - end
if start > 0 {
// copy remaning read bytes from the end to the beginning of a buffer
// so that we will get normal bytes
for i := 0; i < start; i++ {
buf[i] = buf[end+i]
}
}
}
}
}
示例7: NewConnection
// Creates and returns a new Connection object
// Finds token within request URI
func NewConnection(ws *websocket.Conn) (*Connection, error) {
if origin := ws.RemoteAddr(); origin.String() != "http://lab.quantumtrip.org" && origin.String() != "localhost" {
log.Println("Unkown origin: \n\tTo: %s\n\tFrom: %s", origin, ws.Request().RemoteAddr)
//os.Exit(68)
msg := "Please email [email protected] for access"
b, err := json.Marshal(msg)
if err != nil {
log.Panic(err)
}
ws.Write(b)
}
query := ws.Request().URL.Query()
token := GetToken(query)
user, err := getUser(token)
if err != nil {
log.Println(err.Error())
ws.Close()
return nil, err
}
client := ClientInfo{token, ws.Request().RemoteAddr, user}
log.Printf("Connection opened %+v", client)
return &Connection{
make(chan bool),
make(chan interface{}),
client,
ws,
}, nil
}
示例8: SendDeviceStatusMessage
func SendDeviceStatusMessage(ws *websocket.Conn, status DeviceStatus) error {
msg, err := json.Marshal(DeviceStatusMessage{status})
if err != nil {
panic("json.Marshal")
}
_, err = ws.Write(msg)
return err
}
示例9: sendPowerPointExtraReturnInfo
func sendPowerPointExtraReturnInfo(request []byte, extraReturnInfo string, ws *websocket.Conn) {
switch request[1] {
case 'p', 'n', 'r', 'l':
// 傳回目前投影片的備忘稿; 縮圖的網址也直接傳回去,讓瀏覽器判斷
ws.Write([]byte(extraReturnInfo))
}
}
示例10: goRun
func goRun(ws *websocket.Conn, file string) {
var ospath string
gopaths := filepath.SplitList(build.Default.GOPATH)
for _, gopath := range gopaths {
p := filepath.Join(gopath, "src", file)
_, err := os.Stat(p)
if err == nil {
ospath = p
break
}
}
// File was not found
if ospath == "" {
return
}
c := exec.Command("go", "run", ospath)
out, in, err := start(c)
if err != nil {
panic(err)
}
go func() {
for {
buf := make([]byte, 1024, 1024)
n, err := out.Read(buf)
if err != nil {
break
}
n, err = ws.Write(buf[:n])
if err != nil {
break
}
}
ws.Close()
}()
buf := make([]byte, 1024, 1024)
for {
n, err := ws.Read(buf)
if err != nil {
break
}
n, err = in.Write(buf[:n])
if err != nil {
break
}
}
out.Close()
in.Close()
c.Wait()
}
示例11: writer
func writer(ws *websocket.Conn, responses chan []byte) {
defer ws.Close()
for bytes := range responses {
if _, err := ws.Write(bytes); err != nil {
println("Writer Error", err.Error())
return
}
}
}
示例12: echoServer
// Echo the data received on the WebSocket.
func echoServer(ws *websocket.Conn) {
//io.Copy(ws, ws)
for {
buffer := make([]byte, 512)
readData, _ := ws.Read(buffer)
str := string(buffer[:readData])
fmt.Println(str)
ws.Write(buffer[:readData])
}
}
示例13: echoServer
// Echo the data received on the WebSocket.
func echoServer(ws *websocket.Conn) {
//io.Copy(ws, ws)
for {
in := make([]byte, 512)
n, _ := ws.Read(in)
s := string(in[:n])
fmt.Println(s)
ws.Write(in[:n])
}
}
示例14: writeback
// Writes the contents of sMsg back to ws, returning any errors encountered
func writeback(ws *websocket.Conn, sMsg *msgdef.ServerMsg) error {
msg := sMsg.Msg
bytes, err := json.Marshal(msg)
if err != nil {
return err
}
logutil.Log(sMsg.TId, sMsg.UId, fmt.Sprintf("Server Sent: %s", bytes))
_, err = ws.Write(bytes)
return err
}
示例15: RunClient
func RunClient(url string, id string, userKey string) {
rootPath, _ = filepath.Abs(rootPath)
ListenForSignals()
socketUrl := fmt.Sprintf("%s/clientsocket", url)
var ws *websocket.Conn
var timeout time.Duration = 1e8
config, err := websocket.NewConfig(socketUrl, socketUrl)
if err != nil {
fmt.Println(err)
return
}
config.TlsConfig = new(tls.Config)
// Disable this when getting a proper certificate
config.TlsConfig.InsecureSkipVerify = true
for {
time.Sleep(timeout)
var err error
ws, err = websocket.DialConfig(config)
timeout *= 2
if err != nil {
fmt.Println("Could not yet connect:", err.Error(), ", trying again in", timeout)
} else {
break
}
}
buffer, _ := json.Marshal(HelloMessage{"0.1", id, userKey})
if _, err := ws.Write(buffer); err != nil {
log.Fatal(err)
return
}
connectUrl := strings.Replace(url, "ws://", "http://", 1)
connectUrl = strings.Replace(connectUrl, "wss://", "https://", 1)
multiplexer := NewRPCMultiplexer(ws, handleRequest)
if userKey == "" {
fmt.Print("In the Zed application copy and paste following URL to edit:\n\n")
fmt.Printf(" %s/fs/%s\n\n", connectUrl, id)
} else {
fmt.Println("A Zed window should now open. If not, make sure Zed is running and configured with the correct userKey.")
}
fmt.Println("Press Ctrl-c to quit.")
err = multiplexer.Multiplex()
if err != nil {
// TODO do this in a cleaner way (reconnect, that is)
if err.Error() == "no-client" {
fmt.Printf("ERROR: Your Zed editor is not currently connected to zedrem server %s.\nBe sure Zed is running and the project picker is open.\n", url)
} else {
RunClient(url, id, userKey)
}
}
}