<script src="https://www.jb51.net/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); socket.emit('login','30621'); $('form').submit(function(){ socket.emit('chat message',{'toUser':'30342','message':$('#m').val()} ); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); socket.on('privateMessage',function (msg) { $('#messages').append($('<li>').text(msg)); }); </script>
iOS端的处理
iOS在初始化的时候需要一个config字典,config可以配置诸如log日志输出等设置
- (SocketIOClient *)client{ if (!_client) { NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:3000"]; _client = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}]; } return _client; } - (void)connection{ [self.client on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) { NSLog(@"*************\n\niOS客户端上线\n\n*************"); [self.client emit:@"login" with:@[@"30342"]]; }]; [self.client on:@"chat message" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) { if (event[0] && ![event[0] isEqualToString:@""]) { [self.messageArray insertObject:event[0] atIndex:0]; [self.messageTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop]; } }]; [self.client on:@"privateMessage" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) { if (event[0] && ![event[0] isEqualToString:@""]) { [self.messageArray insertObject:event[0] atIndex:0]; [self.messageTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop]; } }]; [self.client on:@"disconnect" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) { NSLog(@"*************\n\niOS客户端下线\n\n*************%@",event?event[0]:@""); }]; [self.client on:@"error" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) { NSLog(@"*************\n\n%@\n\n*************",event?event[0]:@""); }]; [self.client connect]; } //按钮点击事件 - (IBAction)sendMessage:(id)sender { if (self.inputView.text.length>0) { [self.client emit:@"chat message" with:@[@{@"toUser":@"30621",@"message":self.inputView.text}]]; [self.messageArray insertObject:self.inputView.text atIndex:0]; [self.messageTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop]; self.inputView.text = @""; } }