1. 首页
  2. 主题
  3. Go问与答

有个网络库叫gorilla, gorilla有个包叫websocket, websocket包有个方法叫upgrade, 这个upgrade方法的第三个参数怎么用的?

cups_book · · 3163 次点击
我的目标是, 当与客户端建立连接时, 发送一个cookie到客户端去, 必须在这个wss里, 不能使用普通http方法. 我是这么调用的: ``` var responseHeader http.Header //这里我不知道怎么写了 // responseHeader.Set("Set-Cookie", "SS=Q0=5Lb_nQ; path=/search") var conn, err = upgrader.Upgrade(w, r, responseHeader) ``` 方法的原型是这样的 ``` // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie) and the // application negotiated subprotocol (Sec-WebSocket-Protocol). // // If the upgrade fails, then Upgrade replies to the client with an HTTP error // response. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { const badHandshake = "websocket: the client is not using the websocket protocol: " ``` ![image.png](https://static.studygolang.com/190722/6ce4a56f7683e73c5b173b07565d94e5.png)
必须按着我的代码来写,你这样11楼的没用。 upgrader.Upgrade方法会调用http.Hijacker接口,然后利用http连接获得tcp连接,握手时使用tcp连接,写入http格式的响应,我附上的那个连接就ws库写入额外header的信息的实现。 在完成ws握手后,返回了tcp连接封装的ws连接,在Upgrade方法方法后,http就结束,只能操作ws连接。 简单来说Upgrade方法后http就结束了,不能使用http连接,w r对象都是无效的了。
#13
更多评论
.............. 你不觉得,如果是websocket链接上上之后,直接发个message回去,网页监听到后set cookie更靠谱么? 另外gorilla是一个网络库,里面有个websocket的包...
#1
1楼 <a href="/user/jarlyyn" title="@jarlyyn">@jarlyyn</a> 谢谢指正, 我修改了标题. 按照你这个思路的话, 我的问题, 就变成了, 怎么识别客户端, 怎么针对某一个具体的客户端, 发送消息 我搜索了很久, 都没有人用过这第三个参数, 你能帮我看看, 它怎么用吗 https://github.com/gorilla/websocket/tree/master/examples/chat 这个例子, 是讲广播的, 好像没有提到怎么针对某个具体的客户端, 发送消息
#2

用户登录

没有账号?注册

今日阅读排行

    加载中

一周阅读排行

    加载中