iOS 网络编程 XMPP编程
2015-07-08 11:14
501 查看
1、创建流(stream)
2、连接到服务器,同时传输用户名,domain,resource等
3、发送口令
4、发送登陆状态
5、发送消息
6、接收消息
注意:发送接收的两个用户要提前加为好友。
//
// AppDelegate.m
// 0708xcode6.3-01
//
// Created by tianshangrenjian on 15/7/8.
// Copyright (c) 2015年 tianshangrenjian. All rights reserved.
//
#import "AppDelegate.h"
@interface
AppDelegate ()<XMPPStreamDelegate>
@end
@implementation AppDelegate
- (void)createMPPStream
{
XMPPStream *stream=[[XMPPStream
alloc] init];
self.stream=stream;
[stream addDelegate:self
delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0)];
}
- (void)connectToServer
{
[self
createMPPStream];
XMPPJID *myJID=[XMPPJID
jidWithUser:@"test2"
domain:@"tianshangrenjians-MacBook-Air.local"
resource:@"iphone"];
self.stream.myJID=myJID;
self.stream.hostName=@"tianshangrenjians-MacBook-Air.local";
[self.stream
connectWithTimeout:-1
error:nil];
}
- (void)xmppStream:(XMPPStream *)sender didFailToSendPresence:(XMPPPresence
*)presence error:(NSError *)error
{
NSLog(@"on line error %@",error);
}
- (void)xmppStream:(XMPPStream *)sender didSendPresence:(XMPPPresence *)presence
{
NSLog(@"on line ok");
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
// XMPPPresence *presence=[XMPPPresence presenceWithType:@"unavailable"];
// [self.stream sendElement:presence];
//
// });
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
NSLog(@"connect ok");
[self
sendPwdToServer];
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError
*)error
{
NSLog(@"cao:%@",error);
}
- (void)sendPwdToServer
{
[self.stream
authenticateWithPassword:@"1"
error:nil];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
NSLog(@"login ok!");
[self
sendOnLineToServer];
}
- (void)sendOnLineToServer
{
NSLog(@"send ok");
XMPPPresence *presence=[XMPPPresence
presence];
[self.stream
sendElement:presence];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement
*)error
{
NSLog(@"long failed! %@",error);
}
//发送消息
-(void)sendMessage
{
XMPPJID *jid=[XMPPJID
jidWithUser:@"test1"
domain:@"tianshangrenjians-macbook-air.local"
resource:@"fuck"];
XMPPMessage *msg=[[XMPPMessage
alloc] initWithType:@"chat"
to:jid];
[msg
addBody:@"fuck"];
[self.stream
sendElement:msg];
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
NSLog(@"%@",message.body);
[self
sendMessage];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions {
// Override point for customization after application launch.
// [self createMPPStream];
[self
connectToServer];
// [self sendPwdToServer];
return
YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application
and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.yy._708xcode6_3_01" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel !=
nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"_708xcode6_3_01" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator !=
nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"_708xcode6_3_01.sqlite"];
NSError *error =
nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext !=
nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext =
self.managedObjectContext;
if (managedObjectContext !=
nil) {
NSError *error =
nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
@end
2、连接到服务器,同时传输用户名,domain,resource等
3、发送口令
4、发送登陆状态
5、发送消息
6、接收消息
注意:发送接收的两个用户要提前加为好友。
//
// AppDelegate.m
// 0708xcode6.3-01
//
// Created by tianshangrenjian on 15/7/8.
// Copyright (c) 2015年 tianshangrenjian. All rights reserved.
//
#import "AppDelegate.h"
@interface
AppDelegate ()<XMPPStreamDelegate>
@end
@implementation AppDelegate
- (void)createMPPStream
{
XMPPStream *stream=[[XMPPStream
alloc] init];
self.stream=stream;
[stream addDelegate:self
delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0)];
}
- (void)connectToServer
{
[self
createMPPStream];
XMPPJID *myJID=[XMPPJID
jidWithUser:@"test2"
domain:@"tianshangrenjians-MacBook-Air.local"
resource:@"iphone"];
self.stream.myJID=myJID;
self.stream.hostName=@"tianshangrenjians-MacBook-Air.local";
[self.stream
connectWithTimeout:-1
error:nil];
}
- (void)xmppStream:(XMPPStream *)sender didFailToSendPresence:(XMPPPresence
*)presence error:(NSError *)error
{
NSLog(@"on line error %@",error);
}
- (void)xmppStream:(XMPPStream *)sender didSendPresence:(XMPPPresence *)presence
{
NSLog(@"on line ok");
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
// XMPPPresence *presence=[XMPPPresence presenceWithType:@"unavailable"];
// [self.stream sendElement:presence];
//
// });
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
NSLog(@"connect ok");
[self
sendPwdToServer];
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError
*)error
{
NSLog(@"cao:%@",error);
}
- (void)sendPwdToServer
{
[self.stream
authenticateWithPassword:@"1"
error:nil];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
NSLog(@"login ok!");
[self
sendOnLineToServer];
}
- (void)sendOnLineToServer
{
NSLog(@"send ok");
XMPPPresence *presence=[XMPPPresence
presence];
[self.stream
sendElement:presence];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement
*)error
{
NSLog(@"long failed! %@",error);
}
//发送消息
-(void)sendMessage
{
XMPPJID *jid=[XMPPJID
jidWithUser:@"test1"
domain:@"tianshangrenjians-macbook-air.local"
resource:@"fuck"];
XMPPMessage *msg=[[XMPPMessage
alloc] initWithType:@"chat"
to:jid];
[msg
addBody:@"fuck"];
[self.stream
sendElement:msg];
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
NSLog(@"%@",message.body);
[self
sendMessage];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions {
// Override point for customization after application launch.
// [self createMPPStream];
[self
connectToServer];
// [self sendPwdToServer];
return
YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application
and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.yy._708xcode6_3_01" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel !=
nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"_708xcode6_3_01" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator !=
nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"_708xcode6_3_01.sqlite"];
NSError *error =
nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext !=
nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext =
self.managedObjectContext;
if (managedObjectContext !=
nil) {
NSError *error =
nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
@end
相关文章推荐
- libevent参考手册第九章:连接监听器:接受TCP连接 (十一)
- 使用Libevent的快速可移植非阻塞网络编程:异步IO简介 (一)
- Linux 下 ngnix 搭建 http 服务器
- 编译网络驱动启动的方法
- iOS 网络编程 XMPP编程 创建 连接 发送口令 在线状态 等初步操作
- Indy10 控件的使用(2)TidTCpServer组件学习
- 【转】Comet:基于 HTTP 长连接的“服务器推”技术
- 关闭 window 7 映射网络驱动器后,打开里面任何文件的提弹出安全提示的功能
- Nginx服务器中HTTP 301跳转到带www的域名的方法
- 7月初“.网络”域名总量TOP12: 10家实现净增长
- TCP中的MSS解读(转)
- POST http://localhost:8080/admin/getPageDiseaseList net::ERR_INCOMPLETE_CHUNKED_
- STM32W108无线传感器网络节点定位技术
- How to retreive raw post data from HttpServletRequest in java
- How to retreive raw post data from HttpServletRequest in java
- How to retreive raw post data from HttpServletRequest in java
- How to retreive raw post data from HttpServletRequest in java
- STM32W108无线传感器网络嵌入式uCOS-II的移植及实时环境监测
- Facebook网络模拟测试工具ATC使用
- 【计算机网络】期末复习