iOS的swift中的websocket用的库是:starscream。
用websocket接收消息,刚开始连接后,收发消息一直是正常的。
但是过了段时间,大概不到10分钟,然后就无法正常接收到,别的(web)端发送到消息了
然后后来发现android端也出现类似问题:web socket的disconnect也没有监听到
然后也是过了段时间就收不到消息了
搜:
websocket ios not receive
服务器端,默认的设置是:3600000毫秒
搜:
session timeout设置
请教:如何设置session的超时时间,它的默认超时时间是多少?谢谢!!!-CSDN论坛-CSDN.NET-中国最大的IT技术社区
介绍设置Session失效的几种方法 – 51CTO.COM
Java Web开发Session超时设置 – 我的IT技术杂谈 – ITeye技术网站
starscream websocket
daltoniam/Starscream: Websockets in swift for iOS and OSX
后来发现是服务器端,web socket出现异常:EOF
然后好像是IP出错?
出错的IP是192.168.1.107
而不是我的IP 192.168.1.111
WebSocketServerConnection@daf86e8{FILLING}{f=Flusher[queueSize=0,aggregateSize=0,failure=org.eclipse.jetty.io.EofException],g=Generator[SERVER,validating],p=Parser@562e4e1c[ExtensionStack,s=START,c=0,len=0,f=null,p=WebSocketPolicy@58fa4b7e[behavior=SERVER,maxTextMessageSize=65536,maxTextMessageBufferSize=32768,maxBinaryMessageSize=65536,maxBinaryMessageBufferSize=32768,asyncWriteTimeout=60000,idleTimeout=3600000,inputBufferSize=4096]]}
IOState@49fab32e[CLOSED,!in,!out,finalClose=CloseInfo[code=1006,reason=WebSocket Read EOF],clean=false,closeSource=ABNORMAL]
CloseInfo code 1006 reason WebSocket Read EOF
用的是Jetty 9的,官方的websocket
servlet 3.1
websocket – finding out the reason for Web Socket disconnect happened – Stack Overflow
getting the reason why websockets closed – Stack Overflow
websocket – Web socket error close codes specific to browser – Stack Overflow
[2.2] WebSocket api uses a forbidden status code 1006 – Google Groups
IOState CLOSED finalClose 1006 reason WebSocket Read EOF clean false closeSource ABNORMAL
WebSockets closing abnormally? · Issue #225 · mozilla-services/FindMyDevice
websocket disconnect by ios
How to check client is connected in web socket? · Issue #353 · websockets/ws
Unable to keep Websocket alive in background iOS | Apple Support Communities
Unable close/disconnect WebSocket in pause event on iOS
ios websocket connected but not receive
ios websocket can not receive
ios websocket disconnected
iphone – iOS Websocket Library(SocketRocket) gets disconnected at every few seconds – Stack Overflow
acmacalister/jetfire: WebSocket (RFC 6455) client library for iOS & OS X
抽空去试试:
application.idleTimerDisabled
和websocket有没有sendPing
websocket sendping
ios websocket sendping
ios – SocketRocket connection pausing while in background – Stack Overflow
-》在app进入后台,假装借用CLLocationManager去保持位置更新
从而使app的websocket仍然连接
从而保证收发消息正常。。。
-》虽然不好,貌似可以工作?
daltoniam/Starscream: Websockets in swift for iOS and OSX
里面自带:
socket.writePing(NSData()) //example on how to write a ping control frame over the socket!
那就去试试:每隔2分钟,发送一个ping到服务器,看看最后效果
代码加了:
webSocket.writePing(NSData())
变成:
func websocketKeepConnect(){
gLog.debug("gCurUserItem.hasLogined=\(gCurUserItem.hasLogined), gCurUserItem.wsInited=\(gCurUserItem.wsInited)")
if gCurUserItem.hasLogined && gCurUserItem.wsInited {
gLog.info("connect \(webSocket)")
//no matter is connected or not, force connect it to send noop to server to keep websocket alive
webSocket.connect()
webSocket.writePing(NSData())
}
}
结果就可以了:web socket就不会断了。就可以正常收发消息了。
[整理]websocket的ping和pong以及ping的最佳间隔时间
完整代码:
import UIKit
class MainViewController: UITabBarController, UIGestureRecognizerDelegate, WebSocketDelegate, WebSocketPongDelegate {
func initWebSocket(){
dispatchUserInitiated_async({
gLog.debug("gCurUserItem.wsUrl=\(gCurUserItem.wsUrl)")
//ws://jiandao.im/message/user-972b6796-cc82-4058-b29f-9007115116b9/9i8fu0uooq18tunpo9h6grp6gk
self.webSocket = WebSocket(url: NSURL(string: gCurUserItem.wsUrl)!)
self.webSocket.delegate = self
self.webSocket.pongDelegate = self
self.webSocket.connect()
gCurUserItem.wsInited = true
MainViewController.wsFirstInit = true
gLog.debug("websocket \(self.webSocket) has inited and connected")
self.jpushSetAlias()
})
}
func websocketDidConnect(socket: WebSocket) {
//<JianDao.WebSocket: 0x7ffe09cbf9f0>
gLog.debug("\(socket) connected")
if gCurUserItem.hasLogined {
if MainViewController.wsFirstInit {
gLog.debug("is websocket, so not update all conversation")
MainViewController.wsFirstInit = false
} else {
//later sometime, when after disconect then reconnect
//so need update conversation list
SingletonConversationTVC().updateAllConversation()
}
}
startWsKeepConnectTimer()
}
func startWsKeepConnectTimer() {
//Note: makesure when call NSTimer.scheduledTimerWithTimeInterval, need in Loop environment
//so here need in main queue
dispatchMain_async({
self.wsKeepConnectTimer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(WebsocketKeepConnectIntervalInSec),
target: self,
selector:#selector(MainViewController.websocketKeepConnect),
userInfo: nil,
repeats: true)
gLog.info("start websocket keep connect timer: \(self.wsKeepConnectTimer)")
})
}
func StopWsKeepConnectTimer() {
gLog.info("invalidate websocket keep connect timer \(self.wsKeepConnectTimer)")
self.wsKeepConnectTimer.invalidate()
}
func websocketKeepConnect(){
gLog.debug("gCurUserItem.hasLogined=\(gCurUserItem.hasLogined), gCurUserItem.wsInited=\(gCurUserItem.wsInited)")
if gCurUserItem.hasLogined && gCurUserItem.wsInited {
if webSocket.isConnected {
gLog.info("write ping for \(webSocket)")
webSocket.writePing(NSData())
} else {
gLog.info("found disconncted websocket \(webSocket), connect it")
//no matter is connected or not, force connect it to send noop to server to keep websocket alive
webSocket.connect()
}
}
}
func websocketDisconnect(){
if gCurUserItem.wsInited {
StopWsKeepConnectTimer()
gCurUserItem.wsInited = false
gLog.info("disconnect \(webSocket)")
webSocket.disconnect()
}
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
gLog.error("socket=\(socket), error=\(error?.localizedDescription)")
//websocket is disconnected: Optional("Invalid HTTP upgrade")
if gCurUserItem.wsInited {
webSocket.connect()
gLog.debug("try reconnect")
} else {
gLog.warning("not reconnect for websocket not inited")
}
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
let messageData:NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
let messageDict = JSON(data: messageData)
SingletonConversationTVC().processSingleMessageDict(messageDict)
}
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
gLog.info("socket=\(socket) , data.length=\(data.length)")
}
func websocketDidReceivePong(socket: WebSocket) {
gLog.info("socket=\(socket)")
}
然后后来收到了pong的响应:
转载请注明:在路上 » [已解决]websocket过了段时间就收不到消息了