TURN Socket connection failed - iphone

I'm always getting TURN Connection failed. This is the code I'm using
- (void)viewDidLoad {
XMPPJID *jid = [XMPPJID jidWithString:chatWithUser resource:#"Smack"];
[TURNSocket setProxyCandidates:[NSArray arrayWithObjects:chatWithUser, nil]];
TURNSocket *turnSocket = [[TURNSocket alloc] initWithStream:[self xmppStream] toJID:jid];
[turnSockets addObject:turnSocket];
[turnSocket startWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
- (void)turnSocket:(TURNSocket *)sender didSucceed:(GCDAsyncSocket *)socket {
NSLog(#"TURN Connection succeeded!");
NSLog(#"You now have a socket that you can use to send/receive data to/from the other person.");
[turnSockets removeObject:sender];
}
- (void)turnSocketDidFail:(TURNSocket *)sender {
NSLog(#"TURN Connection failed!");
[turnSockets removeObject:sender];
}

Related

GCDAsyncSocket "didReadDataWithTag" Never called with NSOperation subclass

In a "getMyFile" method of some XIB file.
I am creating a object of class "A"(subclass of NSOperation) and adding it to a "myFileQueue"(object of NSOperationQueue).
myFileQueue.MaxConcurrentOperationCount = 1;
Problem : didReadDataWithTag" delegate NEVER called in any case.
#import "GCDAsyncSocket.h"
//and all other required classes are imported correctly
//Class : A
#interface A : NSOperation
{
{
GCDAsyncSocket* socket;
dispatch_queue_t dQueue;
BOOL isWorkDone;
}
}
#implementation A {
-main(){
#autoreleasepool {
isWorkDone = NO;
dQueue = dispatch_queue_create(#"MyDQueue", NULL);
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dQueue];
//NOTE: Even after setting delegateQueue: dispatch_get_main_queue()
//didReadDataWithTag delegate never called
NSError *err = nil;
if (![socket connectToHost:#"192.168.1.142" onPort:12345 error:&err]) // Asynchronous!
{
// If there was an error, it's likely something like "already connected" or "no delegate set"
NSLog(#"I goofed: %#", err);
}
do{
[NSThread sleep:0.2];
}while(!isWorkDone)
}
}
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
NSString* myString= #"testing";
NSData* data=[myString dataUsingEncoding: [NSString defaultCStringEncoding] ];
[socket writeData:data withTimeout:-1 tag:1];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
[socket readDataToData:[GCDAsyncSocket ZeroData] withTimeout:-1 tag:TAG_RESPONSE_HEADER];
}
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
NSLog(#"didReadDataWithTag called...."); //this method never called in any case
isWorkDone = YES;
}
}

Issues regarding gamecenter+ios

I am not knowing anything about gamecentre.I am working on the COCO application
I had gone through gamecenter guide and get able to integrate the game center in my application.
1)
Now the i am able enter the score in the gamecentre through my application.
By doing this:-
- (void) reportScore: (int64_t) score forCategory: (NSString*) category
{
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category] autorelease];
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler: ^(NSError *error)
{
[self callDelegateOnMainThread: #selector(scoreReported:) withArg: NULL error: error];
}];
}
I is working properly uptil yesterday.But now if i tried to update the score it is not updating.Please any one know the reason y the score is not updating in the game center
I had tried to search out but not get anything.
2)I want to send the current latitude & longitude of one player to another.
I came to know that it is possible by GKMATCH
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 1;
request.maxPlayers = 1;
[[GKMatchmaker sharedMatchmaker] findMatchForRequest:request
withCompletionHandler:^(GKMatch *match, NSError *error) {
if (error || !match) {
// handle the error
}
else if (match != nil){
// match found
}}];
/*GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 1;
request.maxPlayers = 1;
GKMatchmakerViewController *mmvc = [[GKMatchmakerViewController alloc] initWithMatchRequest:request];
mmvc.matchmakerDelegate = self;
currentMatch.delegate=self;
[self presentModalViewController:mmvc animated:YES];*/
//[mmvc release];
}
- (void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state {
switch (state){
case GKPlayerStateConnected:
if (match.expectedPlayerCount == 0) {
// start the match
}
break;
case GKPlayerStateDisconnected:
// remove the player from the match, notify other players, etc
break;
}
}
- (void)matchmakerViewControllerWasCancelled:(GKMatchmakerViewController *)viewController{}
// Matchmaking has failed with an error
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFailWithError:(NSError *)error{
}
// A peer-to-peer match has been found, the game should start
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match{
}
// Players have been found for a server-hosted game, the game should start
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindPlayers:(NSArray *)playerIDs{
}
// An invited player has accepted a hosted invite. Apps should connect through the hosting server and then update the player's connected state (using setConnected:forHostedPlayer:)
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didReceiveAcceptFromHostedPlayer:(NSString *)playerID {
}
- (void) sendPosition
{
NSError *error;
NSString* str = #"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
// NSData *packet = [NSData dataWithBytes:&msg length:sizeof(PositionPacket)];
[currentMatch sendDataToAllPlayers: data withDataMode: GKMatchSendDataUnreliable error:&error];
if (error != nil)
{
// Handle the erro.r
}
}
But i dont know why but delegate method of GKMatchmakerViewController is not called i had set the delegate but still and even i ama not able to get GKMATCH (here currentMatch).
So due to this
[currentMatch sendDataToAllPlayers: data withDataMode: GKMatchSendDataUnreliable error:&error];
this method is not working.
as CurrentMatch refrence is 0X0.
Please help me out.How do i send and recive data.
M i doing anything wrong?OR is there any thing else to be done.
Please help me.
Thanks

GCDasyncUdpSocket and wifi Interface

en0 seems to be the wifi interface for Apple iOS devices, but in my code, small multicast client when I specify the interface en0 I'm not receiving anything. Any clue of what could be wrong ? GDCasyncUdpSocket logs don't show any error =>
Binding socket to port(1234) interface((en0))
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
//log test
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Create multicast High Priotity queue
mcastQueue = dispatch_queue_create("mcastQueue", NULL);
dispatch_queue_t high = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_set_target_queue(mcastQueue, high);
// Create UDP Socket
mcastSocket=[[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:mcastQueue];
[mcastSocket setPreferIPv4];
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSError *socketError=nil;
if (![mcastSocket bindToPort:1234 interface:#"en0" error:&socketError]) {
NSLog(#"Failed binding socket to port: %#" ,socketError);
return;
}
if (![mcastSocket enableBroadcast:YES error:&socketError]) {
NSLog(#"Failed enabling broadcast: %#" ,socketError);
return;
}
if (![mcastSocket joinMulticastGroup:#"239.0.0.1" error:&socketError]) {
NSLog(#"Failed joining multicast group: %#" ,socketError);
return;
}
//start receiving multicast data
if (![mcastSocket beginReceiving:&socketError]) {
[mcastSocket close];
NSLog(#"Failed to start receiving: %#" ,socketError);
} else {
NSLog(#"Multicast start receiving");
}
}
Regards
After a year or so of intermittently trying to solve this and giving up, I finally discovered what I believe is the answer to this.
The answer is that you should not bind to an interface when receiving UDP packets. (See https://stackoverflow.com/a/10739443/179216)
Instead you should specify the interface when joining the multicast group:
// Do *not* specify the interface here
if (![mcastSocket bindToPort:1234 error:&socketError]) {
NSLog(#"Failed binding socket to port: %#" ,socketError);
return;
}
if (![mcastSocket enableBroadcast:YES error:&socketError]) {
NSLog(#"Failed enabling broadcast: %#" ,socketError);
return;
}
// This is where you specify the interface
if (![mcastSocket joinMulticastGroup:#"239.0.0.1" onInterface:#"en0" error:&socketError]) {
NSLog(#"Failed joining multicast group: %#" ,socketError);
return;
}

AsyncSocket just read once?

I make simple client server with no CLRFdata, but i give header of message with lenght message self. this is my code :
This method send data
- (void)sendMessage:(NSString *)message {
unsigned char lendata = [message length];
senddata = [NSMutableData dataWithBytes: &lendata length:sizeof(lendata)] ;
[senddata appendData:[message dataUsingEncoding:NSUTF8StringEncoding]];
[socket writeData:senddata withTimeout:-1 tag:0];
}
This method read data from socket lenght = 1 byte until long of code on header.
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
if(bheader){
cdata++;
if(cdata==2){
[data getBytes:&idata];
bheader = NO;
cdata=0;
cmessage = [[NSString alloc] initWithFormat:#""];
}
}
else{
if (message){
cmessage = [[NSString alloc]initWithFormat:#"%#%#",cmessage,message] ;
}
else
NSLog(#"Error converting received data into UTF-8 String");
cdata++;
if(cdata==idata) {
msgComplete=YES;
}
}
if (msgComplete) {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:cmessage forKey:kNotificationMessage];
[notificationCenter postNotificationName:kNotification object:self userInfo:userInfo];
cmessage=#"";
msgComplete=NO;
bheader=YES;
cdata=0;
[cmessage release];
}
[sock readDataToLength:1 withTimeout:-1 tag:0];
}
and this method
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
[sock readDataToLength:1 withTimeout:-1 tag:0];
}
I'm succes send data and recv data from server use this code,
i try make login and server got data and notification, and i recv message with this code, but after that i cant recv message from server when i send message again, but on TCPDUMP i see any message sent to server and server response with a message ?
could any one fix my code where the problem ?
Thanks.

Why can't my devices find each other using this Game Kit connection code?

I'm trying to connect two devices over Bluetooth using Game Kit. The first device is running an application with the following code inside it:
-(void)connect
{
GKPeerPickerController* picker;
picker = [[GKPeerPickerController alloc] init];
picker.delegate = self;
//picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[picker show];
}
- (void)viewDidLoad {
[super viewDidLoad];
peerStatus = kServer;
gamePacketNumber = 0;
currentSession = nil;
gamePeerId = nil;
NSString *uid = [[UIDevice currentDevice] uniqueIdentifier];
gameUniqueID = [uid hash];
[self connect];
}
- (void)peerPickerController:(GKPeerPickerController *)picker didSelectConnectionType:(GKPeerPickerConnectionType)type {
// GKSessionModeClient
// GKSessionModeServer
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeClient];
currentSession.available = YES;
currentSession.delegate = self;
}
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
self.gamePeerId= peerID;
//self.currentSession = session;
self.currentSession.delegate = self;
[self.currentSession setDataReceiveHandler: self withContext:nil];
// Remove the picker.
picker.delegate = nil;
[picker dismiss];
[picker autorelease];
// Start your game
}
- (void)peerPickerControllerDidCancel: (GKPeerPickerController *)picker
{
NSLog(#"peerPickerControllerDidCancel");
picker.delegate = nil;
[picker autorelease];
}
- (void)session: (GKSession*)session peer:(NSString*)peerID didChangeState:(GKPeerConnectionState)state
{
NSLog(#"finding and connecting to others sessions");
if(state == GKPeerStateAvailable){
NSLog(#"aviable and ready to conect");
[session connectToPeer:peerID withTimeout:60];
session.available =NO; //put YES si volem multiconexions sino es tancarĂ  la sesio en conectarse 2
}
}
- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
NSLog(#"lisetn for others sessions");
NSError *error=nil;
if(amAcceptingConnetions){
if(![session acceptConnectionFromPeer:peerID error:&error]){
//Handler error
}
}else{
[session denyConnectionFromPeer:peerID];
}
}
The second device is running another application that uses the same code as above, only with the following piece changed:
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeServer];
The normal window appears on both to indicate that they are searching for other devices, but the two devices don't recognize each other. What could be wrong here?
You need to allocate currentSession if it's not already being allocated. Perhaps try changing:
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeClient];
To this:
self.currentSession = [[GKSession alloc] initWithSessionID:kTankSessionID displayName:nil sesssionMode:GKSessionModeClient];
You may want to also add a check to see if the session is already allocated, and release it if it is before you create a new one. I noticed some improvements in performance and reliability if you reset the session every time your devices try to connect, instead of reusing the same session.
You have to import PeerPickerController along with GameKit/Gamekit.h also. If you want to know more,Please refer this link.
or
http://www.devx.com/wireless/Article/43502/0/page/1