websocket

作者: 绛紫哟 | 来源:发表于2016-05-10 17:40 被阅读583次

    //jetfire-master第三方实现ws的协议

    (1)

    self.socket = [[JFRWebSocket alloc] initWithURL:[NSURL URLWithString:@"ws://localhost:8080"] protocols:@[@"chat",@"superchat"]];

    self.socket.delegate = self;

    (2)实现代理方法

    //开始连接

    -(void)websocketDidConnect:(JFRWebSocket*)socket {

    NSLog(@"websocket is connected");

    }

    //断开连接

    -(void)websocketDidDisconnect:(JFRWebSocket*)socket error:(NSError*)error {

    NSLog(@"websocket is disconnected: %@", [error localizedDescription]);

    //    [self.socket connect];

    }

    //连接成功接收到的字符串,可以使用分割字符串的方法进行解析,也可以将字符串转化为data格式,再转化为json格式进行解析

    -(void)websocket:(JFRWebSocket*)socket didReceiveMessage:(NSString*)string {

    }

    //连接成功接收到的data

    -(void)websocket:(JFRWebSocket*)socket didReceiveData:(NSData*)data;

    (3)可以设置按钮来发送消息(里面加一个定时器,实时接收消息)

    - (IBAction)btnAc:(id)sender

    {

    //开始连接

    [self.socket connect];

    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];

    }

    -(void)timerRun

    {

    NSData * data = [NSData dataWithContentsOfURL:urlPlay];

    [self.socket writeData:data];

    }

    //设置按钮停止信息传输

    - (IBAction)btnStopAc:(id)sender

    {

    [timer invalidate];

    timer = nil;

    //断开连接

    [self.socket disconnect];

    [recorder stop];

    }


    一个demo

    #import#import#import@interface ViewController : UIViewController{

    AVAudioRecorder *recorder;

    NSURL *urlPlay;

    }

    @property (weak, nonatomic) IBOutlet UITextView *textView1;

    @property (weak, nonatomic) IBOutlet UITextView *textView2;

    - (IBAction)btnAc:(id)sender;

    - (IBAction)btnStopAc:(id)sender;

    @end


    #import "ViewController.h"

    #import "JFRWebSocket.h"

    @interface ViewController ()

    {

    NSTimer * timer;

    NSString * unitPath;

    NSMutableDictionary *recordSetting;

    }

    @property(nonatomic, strong)JFRWebSocket *socket;

    @end

    @implementation ViewController

    - (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    [self audio];

    self.socket = [[JFRWebSocket alloc] initWithURL:[NSURL URLWithString:@"ws://localhost:8080"] protocols:@[@"chat",@"superchat"]];

    self.socket.delegate = self;

    }

    - (void)audio

    {

    //录音设置

    recordSetting = [[NSMutableDictionary alloc]init];

    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVSampleRateKey];

    //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)

    [recordSetting setValue:[NSNumber numberWithFloat:16000] forKey:AVSampleRateKey];

    //录音通道数  1 或 2

    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];

    //线性采样位数  8、16、24、32

    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];

    //录音的质量

    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];

    AVAudioSession * session = [AVAudioSession sharedInstance];

    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    [session setActive:YES error:nil];

    NSString *subjectPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1"];

    NSString * gradePath = [subjectPath stringByAppendingString:@"11"];

    unitPath = [gradePath stringByAppendingString:@"22"];

    NSLog(@"unitPath===%@",unitPath);

    if (![[NSFileManager defaultManager] fileExistsAtPath:unitPath])

    {

    [[NSFileManager defaultManager] createDirectoryAtPath:unitPath withIntermediateDirectories:YES attributes:nil error:nil];

    [[NSFileManager defaultManager] createFileAtPath:[unitPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.wav",@"123"]] contents:nil attributes:nil];

    }

    NSURL * url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/123.wav",unitPath]];

    urlPlay = url;

    }

    -(void)websocketDidConnect:(JFRWebSocket*)socket {

    NSLog(@"websocket is connected");

    }

    -(void)websocketDidDisconnect:(JFRWebSocket*)socket error:(NSError*)error {

    NSLog(@"websocket is disconnected: %@", [error localizedDescription]);

    //    [self.socket connect];

    }

    -(void)websocket:(JFRWebSocket*)socket didReceiveMessage:(NSString*)string {

    //    NSLog(@"Received text: %@", string);

    //    [_textView2 setText:string];

    NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *  dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

    NSLog(@"dic===%@",dic);

    NSString * status = [NSString stringWithFormat:@"%@",dic[@"status"]];

    if ([status isEqualToString:@"0"])

    {

    NSString * transcript = dic[@"result"][@"hypotheses"][0][@"transcript"];

    [_textView2 setFont:[UIFont systemFontOfSize:16]];

    [_textView2 setText:[transcript lowercaseString]];

    }

    }

    - (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

    }

    - (IBAction)btnAc:(id)sender

    {

    NSError *error;

    //初始化

    recorder = [[AVAudioRecorder alloc]initWithURL:urlPlay settings:recordSetting error:&error];

    //开启音量检测

    recorder.meteringEnabled = YES;

    recorder.delegate = self;

    //创建录音文件,准备录音

    if ([recorder prepareToRecord]) {

    //开始

    [recorder record];

    }

    [self.socket connect];

    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];

    }

    -(void)timerRun

    {

    NSData * data = [NSData dataWithContentsOfURL:urlPlay];

    [self.socket writeData:data];

    //    NSLog(@"size===%llu",[[[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/123.wav",unitPath] error:nil] fileSize]);

    }

    - (IBAction)btnStopAc:(id)sender

    {

    [timer invalidate];

    timer = nil;

    [self.socket disconnect];

    [recorder stop];

    }

    相关文章

      网友评论

          本文标题:websocket

          本文链接:https://www.haomeiwen.com/subject/ctyyrttx.html