英文:
http server Websocket and serving a static page
问题
考虑以下示例:
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
"os"
)
type MessageReceived struct {
Name string
Nbmsg int
}
func Echo(ws *websocket.Conn) {
msg := new(MessageReceived)
for {
websocket.JSON.Receive(ws, &msg)
fmt.Printf("Received message: %+v\n", msg)
if err := websocket.JSON.Send(ws, msg); err != nil {
fmt.Println("Can't send echo")
break
}
//os.Exit(0)
}
}
func checkError(err error) {
if err != nil {
log.Printf("Fatal error: %s\n", err.Error())
os.Exit(1)
}
}
func main() {
http.Handle("/s", websocket.Handler(Echo))
fs := http.FileServer(http.Dir("web"))
err := http.ListenAndServe(":8081", fs)
checkError(err)
}
页面和静态文件被提供,但是当我尝试从JavaScript连接到WebSocket时,我得到以下错误:
WebSocket connection to 'ws://localhost:8081/s' failed: Error during WebSocket handshake: Unexpected response code: 404
我唯一能让它工作的方法是通过从不同的Go应用程序服务器提供静态文件,并且还使用两个不同的端口在本地主机上提供WebSocket,我在上面的示例中漏掉了什么?我如何从同一个服务器提供文件和WebSocket?
英文:
Consider the following sample
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
"os"
)
type MessageReceived struct {
Name string
Nbmsg int
}
func Echo(ws *websocket.Conn) {
msg := new(MessageReceived)
for {
websocket.JSON.Receive(ws, &msg)
fmt.Printf("Received message: %+v\n", msg)
if err := websocket.JSON.Send(ws, msg); err != nil {
fmt.Println("Can't send echo")
break
}
//os.Exit(0)
}
}
func checkError(err error) {
if err != nil {
log.Printf("Fatal error: %s\n", err.Error())
os.Exit(1)
}
}
func main() {
http.Handle("/s", websocket.Handler(Echo))
fs := http.FileServer(http.Dir("web"))
err := http.ListenAndServe(":8081",fs)
checkError(err)
}
The page and static files gets served but when but i try to connect to the websocket from javascript i get
WebSocket connection to 'ws://localhost:8081/s' failed: Error during WebSocket handshake: Unexpected response code: 404
The only way i could make it work is by serving static files from a different go application server and serving the websocket also from a separate server application using 2 different ports on the local host, what am i missing in the above sample? how could i serve files and the websocket from the same server?
答案1
得分: 5
你正在将websocket.Handler
分配给DefaultServeMux
,但在ListenAndServe
调用中只使用了FileServer
处理程序。
在DefaultServe mux中添加FileServer处理程序,使用一些不冲突的前缀:
func main() {
http.Handle("/s", websocket.Handler(Echo))
http.Handle("/f", http.FileServer(http.Dir("web")))
err := http.ListenAndServe(":8081", nil)
checkError(err)
}
英文:
You're assigning the websocket.Handler
to the DefaultServeMux
, but only using the FileServer
handler in your ListenAndServe
call.
Add the FileServer handler to the DefaultServe mux too, with some non-conflicting prefix:
func main() {
http.Handle("/s", websocket.Handler(Echo))
http.Handle("/f", http.FileServer(http.Dir("web"))
err := http.ListenAndServe(":8081", nil)
checkError(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论