#import "SRWebSocket.h"
#import <UIKit/UIKit.h>
#import "SocketRocket.h"
@interface ViewController : UIViewController<SRWebSocketDelegate>
@property (nonatomic,strong)SRWebSocket *webSocket;
@end
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *showTxt;
@end
@implementation ViewController
- (void)viewWillAppear:(BOOL)animated{
[self Reconnect];
}
- (void)viewDidDisappear:(BOOL)animated{
// Close WebSocket
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = nil;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
//初始化
- (void)Reconnect{
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://echo.websocket.org"]]];
self.webSocket.delegate = self;
self.title = @"Opening Connection...";
[self.webSocket open];
}
//成功连接
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
NSLog(@"Websocket Connected");
self.title = @"Connected!";
}
//连接失败,打印错误信息
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
NSLog(@":( Websocket Failed With Error %@", error);
self.title = @"Connection Failed! (see logs)";
self.webSocket = nil;
}
//接收服务器发送信息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
NSLog(@"Received \"%@\"", message);
self.showTxt.text = message;
}
// 长连接关闭
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
NSLog(@"WebSocket closed");
self.title = @"Connection Closed! (see logs)";
self.webSocket = nil;
}
//该函数是接收服务器发送的pong消息
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload {
NSString *reply = [[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding];
NSLog(@"%@",reply);
}
- (IBAction)sendAction:(id)sender {
[self.view endEditing:YES];
// WebSocket
if (self.webSocket) {
[self.webSocket send:@"test success"];
}
}
~~
本文来自于[](ttps://www.cnblogs.com/ningmengcao-ios/p/5941993.html)
网友评论