Sending Strings Over GKSession - How to stop some craziness?

Sounds simple, right? But the tricky part is I am trying to retain the header structure from GKTank... I am quite desperate for help at this point as I've been flailing around on this all day and all night....
All my other events use this structure already and work just fine..and after a ton of trial and error I'm very close... hoping I can get one of you experts to take a look. The issue is that when my strings are less than 8 characters, the results get very strange....
Here's the relevant code: (kMaxPacketSize is a constant of 1024)
To send Data: (this is straight from GKTank, actually)
- (void)sendNetworkPacket:(GKSession *)session packetID:(int)packetID withData:(void *)data ofLength:(int)length reliable:(BOOL)howtosend {
static unsigned char networkPacket[kMaxPacketSize];
const unsigned int packetHeaderSize = 2 * sizeof(int); // we have two "ints" for our header
if(length < (kMaxPacketSize - packetHeaderSize)) { // our networkPacket buffer size minus the size of the header info
int *pIntData = (int *)&networkPacket[0];
// header info
pIntData[0] = packetNumber++;
pIntData[1] = packetID;
// copy data in after the header
memcpy( &networkPacket[packetHeaderSize], data, length );
NSData *packet = [NSData dataWithBytes: networkPacket length: (length+8)];
if(howtosend == YES) {
[session sendDataToAllPeers:packet withDataMode:GKSendDataReliable error:nil];
} else {
[session sendDataToAllPeers:packet withDataMode:GKSendDataUnreliable error:nil];
In this particular case, I began by calling the above method thusly:
NSString *myText = self.myLabel.text
NSInteger len = [myText length];
[self sendNetworkPacket:mySession packetID:NETWORKTEXTEVENT withData:myText ofLength:(len*2)+1 reliable:YES];
and unwrapping like this on the other end:
NSString *pStringData = (NSString *)&incomingPacket[8];
Works like a charm... strings show up just fine on the other device.... except when the string is less than 8 characters...this causes crashes of EXCBADACCESS on the receiving device. When I check values for these short strings prior to sending over GKSession, the memcpy command does not properly embed the string into 'networkPacket' and keeps remnants from the last string that was transmitted.
So, in an attempt to work around what is probably a flaw in my logic, I decided to see what happens if I pad the beginning and end of these short strings to make them over 8 characters, by defining another string 'spacer' and then sending a padded string instead of myText:
NSString *spacer = @"zZzZ";
NSString *bufText = [spacer stringByAppendingString:[myText stringByAppendingString:spacer]];
len = [bufText length];
[self sendNetworkPacket:mySession packetID:NETWORKTEXTEVENT withData:bufText ofLength:(len*2)+1 reliable:YES];
This got rid of the issues with memcpy, and now all strings are embedded in 'networkPacket' properly, some just have the spacers on the beginning and end... no problem, right? I figured I'd just filter out the spacers on the other end, but guess what? I have even tried using the same code to disassemble the packet, prior to sending it, exactly the way I do on the receiving device... it disassembles fine, and I can re-create the string from the raw packet I send....
However... (and this ONLY happens on the strings that have been padded) when I receive the data through GKSession I get totally random characters and even lengths! Sometimes I get odd system strings like 'tpenable' or 'uni0164' ... it's so bizarre... I don't understand what is making the padded strings get treated differently.... I tried padding all strings just to check and then they all act like this when transmitted... and again when I use the following code, prior to sending the packet, both test1 and test2 look fine:
NSString *test1 = (NSString *)&networkPacket[8];
unsigned char *testPacket = (unsigned char *)[packet bytes];
NSString *test2 = (NSString *)&testPacket[8];
NSLog (@"netPacket");
NSLog (test1);
NSLog (@"Packet");
NSLog (test2);
If you have any ideas, I'd really appreciate it!
Message was edited by: Tech Guru

[dataString bytes] returns a +const void*+ type. The compiler is complaining because you passed that +const void*+ pointer to a method that declared the 3rd arg to be a void*. The difference between the two pointers is that the first type doesn't want you to change the bytes that it's pointing to, while the second type doesn't care.
For example:
- myMethod:(const char *)foo {
foo[3] = 'A'; // changing the value of the 4th byte at address foo
In the above, the compiler should warn that your method changed the data which was referenced by a const char* type.
But sendNetworkPacket doesn't do anything naughty like the above, it just copies the data at the given addy into a buffer. So you could have declared the data param as const void* like this:
- (void)sendNetworkPacket:(GKSession *)session packetID:(int)packetID withData:(const void *)data ofLength:(int)length reliable:(BOOL)howtosend;
The above change should get rid of the warning. If the compiler thinks you're changing that data in sendNetworkPacket (we know you're not doing that, but it's hard to argue with a compiler), you'll then get a new warning to that effect. In that case you might as well put a type cast in the call. I.e. take 'const' back out of the method declaration, and cast the arg in the call like this:
[self sendNetworkPacket:mySession packetID:NETWORKTEXTEVENT withData:(void*)[dataString bytes] ofLength:len reliable:YES];
The first try is preferable, since we like to avoid type casts, and since (I assume) sendNetworkPacket really doesn't want to change that data. But if the compiler won't cooperate, the second way will always work for you.
Btw, putting the text into a NSData object is fine by me, but you could've also used any number of NSString methods that aren't deprecated (e.g. [myText UTF8String]). No need to go there now though. I'm guessing your early problems with some perfectly good methods were due to data type glitches. Because of mismatched data types, you may have abandoned the correct approach and gone down the wrong path.
Once things got to the point where a NSString pointer was sent to memcpy, I think all of us were at risk of falling into darkness. I stared at the code for a very long time, wondering if everyone in the World but me knew that trick. Next time you get a data type error, maybe post the code here and let us try and help out while the problem is still easy to solve, ok?
All the best,
Ray

Similar Messages

  • I would like to know how i stop some albums ive bought from transfering to my iphone i delete them from itunes but when i sync my phone they transfer from my iphone this is a pain some one please help!!

    I would like to know how i stop some albums ive bought from transfering to my iphone i delete them from itunes but when i sync my phone they transfer from my iphone this is a pain some one please help!!

    Burb79 wrote:
    I thought of that one two tried it but still no joy. I have an ipad2 as well which I set up to not sync any music to it but for some reason the albums have got onto that as well. im thinkin its somthing to do with the dam cloud thing
    Go to Settings/ Store and under the category "Automatic Downloads" you can turn OFF the automatic download of purchases to your device (this needs to be done for each device). There's also a setting in iTunes just for automatic pushes to your iTunes library.
    To remove a purchase you've made directly to your device, you can either:
    a- Swipe across the song title from left to right and press Delete, or
    b- If you auto-sync your device, connect to iTunes and click on the Music tab where you define your sync settings (the Music tab is to the right of the overall Summary page of your device). At the bottom of the Music tab you'll see direct purchases that are on your device -- simply un-check those and click "Apply" or "Sync" to remove them.
    c- If you manually manage music on your device, connect to iTunes and click the small arrow to the left of your device name, and then click on the Music folder under your device. Then navigate to the item(s) you want to remove and then delete them.
    To prevent things from syncing from your library to your device, there are many ways to do that (un-checking things in your library is one way, but not the best IMO). Might want to read the manual or some online tutorials on iTunes if you want to learn more.

  • How do I send strings over a TCP/IP LAN N/W

    I want to send string information over LANs which can be viewed on Hyperterminal in PCs on the N/W
    Pls help me out
    Solved!
    Go to Solution.

    Are you trying to broadcast a message on your LAN? If so you'd need to use UDP (since it's a connectionless protocol) and use the broadcast address for your subnet. You'd have to check with your network admin as to what that is, though it's probably x.x.x.255 or 255.255.255.255. TCP requires a connection so for TCP/IP you'd need to send the message to each individual IP address. Alternatively, if you're on Windows you could use the "net send" command using System Exec.

  • We were wondering how you stop some apps from running with out deleting them something like a task manager and in my settings im missing the application button in it how do i get it back and stop some apps its making it run really slow

    how do you stop apps with out deleting them i have looked for something like a task manager and nothing and researched about it and it says to go into your settings and then click applications but i dont have one can someone please help[ me thank you

    Double click the Home button. The bottom row shows the recently used apps. Touch and hold the app until they all start to wiggle then tap the circled minus sign by apps you want to remove. Press the Home button to return to normal.
    However, that is recently used apps not apps doing something. Some apps will do things all the time/periodically like checking for Notification, new mail. Yu can turn those off in the apps themselves.
    Just what are you trying to accomplish?

  • How to stop some apple id call my apple id and/ or my phone number by face time

    Hi there, my niece lost her iPod touch at school and in there had my phone number and my apple Id. Unknow people stolen the iPod keep calling me by face time even I changed my apple id. Can someone help me to stop them bother me like that way. They cover their face by blanket and talk crazy, if I do not accept,they will call me again and again. I am stuck ! Help me please !

    You can delete the iCloud account from her phone by going to Settings>iCloud, scroll to the bottom and choose Delete Account.  I believe you will get a prompt asking if you want to remove or keep the data on the phone; if you don't want your contacts on her phone choose delete.  As far as the contact on your old SIM card, if it is the same size as the iPhone SIM card you can put it in the iPhone and import the contacts (see http://support.apple.com/kb/HT4994).  If the SIM card won't fit, then you would need to either export the contacts to your computer using appropriate software, upload your contacts to a cloud service so you can download them to your computer, or in some cases take it and your iPhone to your retailer and ask them if they can do the transfer for you.  (It's also possible to cut a SIM card down to fit but it can be tricky to get it right.  There are articles on this if you search with Google.)  This video might help: http://www.youtube.com/watch?v=ypZpYNpfa9E.

  • How to stop some keyevent listening ?

    Hi,
    I have a number of JTextPane organized as cells of a table and I would like to go from one to another with the enter/tab key; but when I do that, in addition to jump from a cell to another, their is a enter/tab keyevent send to the JTextPane that had the focus. Is it possible to configure the JTextPane to ignore enter and tab key ?
    Thanks a lot

    ok, I'v just implemented it, it woks!
    I didn't know that the component send envents before processing it itself, I've learn a really useful thing.
    In fact it is explicitly writed in the API of the InputEvent class:
    Thanks a lot

  • How to stop this crazy behaviour? CC = crappy cloud.

    I have tried CC for a short time. I don't like it, so I removed it completely.
    Next I installed CS6 again.
    Install proceeds without any errors. Next update all. Done.
    So far so good, but when I try to open Illustrator or Premiere Pro, I get this:
    I have no CC subscription. I installed with a serial number, so what the heck is Adobe doing?

    Hi All,
    You may any one of try this,
    1.Run the CC Cleaner tool to completely uninstall by the following method.
    .http://www.adobe.com/support/contact/cscleanertool.html
    2.Uninstall Adobe Creative Suite on Windows
    A.Open the Add or Remove Programs Control Panel (Windows XP) or the Programs And Features Control Panel (Windows Vista/Windows 7/Windows 8).  B.Select the Adobe Creative Suite product and click Remove or Uninstall. Please Check the preference before uninstalling
    C. After uninstall is completem,restart your system and close all open applications.
    3.Uninstall Adobe Creative Suite on Mac OS
    A.Navigate to /Applications/Utilities/Adobe Installers.
    B.Double-click the Adobe Creative Suite product uninstaller.Please Check the preference before uninstalling
    C. After uninstall is completem,restart your system and close all open applications.
    Now launch the product.This might be useful.
    Regards,
    Rajshree

  • Not Sure How To Send String

    I'm totally new to trying to network using Java and extremely poor at networking in general so bear with me here.
    I'm trying to make a top down shooter and currently the application allows the user to either play as host or connect to a host but all the network communication handling I'm doing involves creating strings, sending them along the connection and interpreting the strings on their reciept.
    The problem I'm having is I keep getting an unexpected end of file exception when it tries to read in the string.
    I used a basic IM application as an example of how to connect and send info in Java, which is where I got the idea to use in.readUTF and out.writeUTF to send string information but upon looking into this problem it seems to me that read/writeUTF is not really designed for strings and there should be something else I should use instead but I'm not sure what?
    Also I'm using this to communicate point information of each player and as I understand it I should be using TCP to do this as that was what the example I'm using said it used. Though I think it might be more useful to use UDP as it's faster and it shouldn't matter if I drop a packet or two, though I'm not sure where in my code it specifies a difference between the two and if that really is the best idea.
    Here's a zip of my netbeans project, though be warned it's VERY messy, probably the messiest code I've ever written, not to mention hacky as well: http://rapidshare.com/files/369943023/KerazehDood.zip
    Any help would be great.
    Thanks.
    Edited by: ThePermster on Mar 30, 2010 6:59 AM

    Thanks that seems to make much more sense, still having some troubles though.
    Ok so now the majority of it seems to be working and it seems to be sending the String just fine. And I'm having it send the String to the BufferedWriter "out" and then using the newLine() method to send a carriage return but the BufferedReader on "in" seems to not detect the carriage return.
    I have it doing a readLine() so that (as I understand it) it should be blocking, waiting until an end of line character so I assume each call of newLine() should have it pick up something but a quick breakpoint shows that it never stops blocking on readLine().
    I assume the connection is fine because the application running as server uses the socket object returned by the accept() method.
    Is there something I've perhaps misunderstood about the BufferedReader's readLine() method?
    Here's the new version of my netbeans project:
    http://rapidshare.com/files/371224512/KerazehDood.rar
    Also on a different line of questioning, I'm just wondering about socket convention.
    I was thinking it'd be useful in a game similar to what I'm attempting to make to not only send player position information but also client keypress information, I was just wondering, if you're doing something like that would it be frowned upon to use two separate ports? I think it would make the implementation far more legible and easy to structure but wasn't sure if applications usually try to stick to only one port or not.
    Thanks.
    Edited by: ThePermster on Apr 2, 2010 10:54 AM

  • HT4914 I often record songs at a particular tempo, iTunes Match will then match it and send it back to me at the original tempo, is there anyway I can stop some songs from being matched. At the moment I have turned match off. But I would like to sync play

    I often record songs at a particular tempo, iTunes Match will then match it and send it back to me at the original tempo, is there anyway I can stop some songs from being matched. At the moment I have turned match off. But I would like to sync playlists.

    How old was this backup? It sounds like it was at least several weeks old.
    You can look directly in the TM backup for the music.
    1. Connect to the external HDD the backup is kept on.
    2. Open a Finder window and select the backup drive in the left hand panel. Double click into the folders until you see a list of folders with dates.
    These are the incremental backups. You can start at the top or the bottom of the list but I suggest you double Latest/<HDD Name>/Users/<Account Name>/Music/iTunes/iTunes Media/Music. From this location you can start looking for the "missing" music. When/if you find it you can simply drag-n-drop to ~/Music/iTunes/iTunes Media/Music on the internal HDD.
    If the music is actually not in the backups (for whatever reason) then you've got a problem.
    You can download the uploaded files from the cloud by deleting the affected tracks from the iTunes library (but not the cloud!), highlighting multiple tracks at once, right-clicking and choosing "download."

  • How to send string data through socket!

    Is there any method to send string data over socket.
    and if client send string data to server,
    How to get that data in server?
    Comments please!

    Thank for your kind answer, stoopidboi.
    I solved the ploblem. ^^;
    I open the source code ^^; wow~~~~~!
    It will useful to many people. I spend almost 3 days to solve this problem.
    The program works like this.
    Client side // string data ------------------------> Server side // saving file
    To
    < Server Side >
    * Server.java
    * Auther : [email protected]
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Server extends JFrame
         private JTextField enter;
         private JTextArea display;
         ObjectInputStream input;
         DataOutputStream output;
         FileOutputStream resultFile;
         DataInputStream inputd;
         public Server(){
              super("Server");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent ev){
                             //None
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display),
                     BorderLayout.CENTER);
              setSize(300, 150);
              show();
         public void runServer(){
              ServerSocket server;
              Socket connection;
              int counter = 1;
              display.setText("");
              try{
                   server = new ServerSocket(8800, 100);
                   while(true){
                        display.append("Waiting for connection\n");
                        connection = server.accept();
                        display.append( counter + " connection is ok.\n");
                        display.append("Connection " + counter +
                             "received from: " + connection.getInetAddress().getHostName());
                        resultFile = new FileOutputStream("hi.txt");
                        output = new DataOutputStream(resultFile);
                        output.flush();
                        inputd = new DataInputStream(
                             connection.getInputStream()
                        display.append("\nGod I/O stream, I/O is opened\n");
                        enter.setEnabled(true);
                        try{
                             while(true){
                                  output.write(inputd.readByte());
                        catch(NullPointerException e){
                             display.append("Null pointer Exception");
                        catch(IOException e){
                             display.append("\nIOException Occured!");
                        if(resultFile != null){
                             resultFile.flush();
                             resultFile.close();
                        display.append("\nUser Terminate connection");
                        enter.setEnabled(false);
                        resultFile.close();
                        inputd.close();
                        output.close();
                        connection.close();
                        ++counter;
              catch(EOFException eof){
                   System.out.println("Client Terminate Connection");
              catch(IOException io){
                   io.printStackTrace();
              display.append("File is created!");
         public static void main(String[] args){
              Server app = new Server();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runServer();
    < Client side >
    * Client.java
    * Auther : [email protected]
    package Client;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame
         private JTextField enter;
         private JTextArea display;
         DataOutputStream output;
         String message = "";
         public Client(){
              super("Client");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             //None
              c.add(enter, BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display), BorderLayout.CENTER);
              message = message + "TT0102LO12312OB23423PO2323123423423423423" +
                        "MO234234LS2423346234LM2342341234ME23423423RQ12313123213" +
                        "SR234234234234IU234234234234OR12312312WQ123123123XD1231232" +
                   "Addednewlinehere\nwowowowwoww";
              setSize(300, 150);
              show();
         public void runClient(){
              Socket client;
              try{
                   display.setText("Attemption Connection...\n");
                   client = new Socket(InetAddress.getByName("127.0.0.1"), 8800);
                   display.append("Connected to : = " +
                          client.getInetAddress().getHostName());
                   output = new DataOutputStream(
                        client.getOutputStream()
                   output.flush();
                   display.append("\nGot I/O Stream, Stream is opened!\n");
                   enter.setEnabled(true);
                   try{
                        output.writeBytes(message);
                   catch(IOException ev){
                        display.append("\nIOException occured!\n");
                   if(output != null) output.flush();
                   display.append("Closing connection.\n");
                   output.close();
                   client.close();
              catch(IOException ioe){
                   ioe.printStackTrace();
         public static void main(String[] args){
              Client app = new Client();
              app.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                             System.exit(0);
              app.runClient();

  • When send email with emoticons to a pc user, emoticons show as an empty box. Also, email content has a symbol on every line. How to stop this from happening?

    When send email with emoticons to a pc user, emoticons show as an empty box. Also, email content has a > symbol on every line. How to stop this from happening?

    Dear Mr. Toad (my all-time favorite ride at Disneyland ;-) ..
    Thanks so much for your detailed reply.. my netbook is in the bedroom, turned off.. I (so far) only use it in the evening, in the bedroom.. I've saved your response, and will try your suggestions, and let you know if they solve the problem I described. I really appreciate you taking the time to post such a detailed reply..
    I can't answer your Thunderbird "configuration" questions, because I'm in the living room, using the crap Vista laptop, on which I plan to install Thunderbird, and then take Windoze Mail out in the street and drive over it a few times.. I'll get back to you one way or the other, and let you know if your instructions solved the problem, or not..
    I don't understand why Thunderbird "out of the box", so to speak, simply doesn't forward HTML emails with embedded graphics, (like Outlook Excess, and Winblows Mail do).. without having to go through those steps. I personally HATE HTML email, but over the years, it's become more and more prevelant.. so it's a problem I must fix..
    Thanks again..
    Harv..

  • My daughter has an iphone 5s and I have her old 3GS. She receives all my imessages that I rcv or send to other people. Can anyone advise how to stop this? we have removed the 3gs from her itunes account but it hasn't stopped the issue.

    My daughter has an iphone 5s and I have her old 3GS. She receives all my imessages that I rcv or send to other people. Can anyone advise how to stop this? we have removed the 3gs from her itunes account but it hasn't stopped the issue.

    There are a lot of posts in the forums today with people having problems with iMessage.   There was also a published outage yesterday, so it's possible there are still some issues that may be impacting you both.
    I would just wait it out - I'm sure it will be sorted out soon.

  • HT2515 How do I stop some one from contacting me?

    How do I stop some from contacting me on ichat?

    Hi,
    In an AIM Buddy list.
    Go to iChat Menu > Preferences > Accounts and then the specific account > Security tab
    In here select Block specific People and add the Screen name of the person you want to block.
    If Jabber (Googletalk, Facebook or other) and if they are already in your Buddy List then Right click them to Remove them or use the Buddies Menu and De-Authorise them.
    Basically AIM allows anyone to "call" your Screen name and only the Block or the restricted Allow options are the way to control who can contact you.
    With Jabber they can Invite you to be a Buddy but if they are not Authorised (and then in the list) they cannot send you messages.
    8:18 pm      Wednesday; December 4, 2013
      iMac 2.5Ghz 5i 2011 (Mavericks 10.9)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
     Couple of iPhones and an iPad

  • My iPhone 5 charger stopped working. It's under warranty and I want to send it back. How do I initiate that process? The website keeps sending me in circles.  I'm getting an error message when I put in my serial number.  Why is this so difficult?

    My iPhone 5 charger stopped working. It's under warranty and I want to send it back. How do I initiate that process? The website keeps sending me in circles.  I'm getting an error message when I put in my serial number.  Why is this so difficult?

    If posible you will find visiting a store by far the simplest way of getting a solution
    Which Country
    are you in ?
    Have you checked the lightning socket on iPhone doesn't have lint or fluff in it
    solves majority of such issues

  • How to stop the Sending USSD message on my iPad since upgrading. The eKit SIMM worked fine on my older iPad. Thanks

    How to stop the Sending USSD message on my iPad since upgrading. The eKit SIMM worked fine on my older iPad. Thanks

    Wiping my phone, restoring from backup, AND wiping all iTunes related files (from a search in Library and in Music) seems to have stopped this behavior.
    (I couldn't wipe the iTunes files on the machine with my media and apps, but I did so on the other machine--where I only sync contacts, calendars and bookmarks. My iTunes library is empty there anyway.)
    I don't know if this relates to an "app synching" issue that iTunes 9.0.1 fixed. Could be.

Maybe you are looking for