ipv6

//
//  CommonInterface.m
//  Unity-iPhone
//
//  Created by wuruijian on 14-9-28.
//
//

#import "UnityAppController.h"
#import "CommonAppDelegate.h"
#import "PushService.h"
#import "U3DInterface.h"
#import "Reachability.h"
#import "sys/utsname.h"
#import "APService.h"
#import <sys/sysctl.h>
#import <mach/mach.h>


CommonAppDelegate *appInstance;


/
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"
/



#if defined(__cplusplus)
extern "C"{
#endif
    
NSString *GetModel();
int GetAvailableMemory();
char* _MakeStringCopy( const char* string);
    
void SDK_Init()
{
    NSLog(@"------------SDK_Init");
    
    //启动推送
    [[PushService GetInstance] Push];
    
    //获取网络状态
    if (appInstance != nil)
        [appInstance ListenNetChange];
    
    //获取手机信息:手机型号~系统版本号~唯一标识
    UIDevice *device = [UIDevice currentDevice];
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *cid = [userDefaults stringForKey:@"cfuuid"];
    if (nil == cid)
    {
        CFUUIDRef cfuuid =CFUUIDCreate(kCFAllocatorDefault);
        cid =(NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
        [userDefaults setObject:cid forKey:@"cfuuid"];
        [userDefaults synchronize];
    }
    
     NSDictionary *dic= [appInstance getIPAddresses];
    
    NSString *phoneInfo = [NSString stringWithFormat:@"%@~%@~%@~%d~%@", GetModel(), [device systemVersion], cid, GetAvailableMemory()
                           , [appInstance CheckIpv4:dic]];
    
    NSLog(@"dic:    %@",dic);
    NSLog(@"ip:    %@",[appInstance CheckIpv4:dic]);  
    
    
    U3DSendMessage(ON_GET_INFO, phoneInfo);
}
    
void Exit()
{
    NSLog(@"== sdk Exit ==");
}
    
void UpdatePlayerInfo(const char* info)
{
    //[appInstance UpdatePlayerInfo: [NSString stringWithUTF8String:info]];
    
    NSString *customInfo=[NSString stringWithUTF8String:info];
    
    NSArray *array= [customInfo componentsSeparatedByString:@" "];
    if([array count]==9)
    {
        appInstance.mRoleID=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:0]];
        appInstance.mNickName=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:1]];
        appInstance.mRoleLvl=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:2]];
        appInstance.mServerID=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:3]];
        appInstance.mServerName=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:4]];
        appInstance.mGold=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:5]];
        appInstance.mVipLvl=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:6]];
        appInstance.mFactionName=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:7]];
        appInstance.mCreateRoleTime=[[NSString alloc] initWithFormat:@"%@",[array objectAtIndex:8]];
    } 
    [appInstance UpdatePlayerInfo: customInfo];
    
}
    
void GoAppStore()
{
    [appInstance GoAppStore];
}

void ShieldPush(bool isPush)
{
    if ([UIApplication sharedApplication] == nil) {
        return;
    }
        
    NSLog(@"------------ShieldPush%@", (isPush ? @"true" : @"false"));
    if (isPush)
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    else
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
}
    
int GetMarket()
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"sdkInfo" ofType:@"plist"];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    NSInteger market = [[[dictionary objectForKey:@"sdkInfo"] objectForKey:@"market"] intValue];
    NSLog(@"market:%d", market);
    return market;
}
    
const char* GetChannel()
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"sdkInfo" ofType:@"plist"];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *channel = [[dictionary objectForKey:@"sdkInfo"] objectForKey:@"channel"];
    NSLog(@"channel:%@", channel);
    return _MakeStringCopy([channel UTF8String]);
}
    
NSString *GetGameName()
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"sdkInfo" ofType:@"plist"];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *gameName = [dictionary objectForKey:@"CFBundleDisplayName"];
    NSLog(@"game name:%@", gameName);
    return gameName;
}
    
void PopupDialog(const char* title, const char* content)
{
    if (appInstance != nil)
        [appInstance showAlertView : [NSString stringWithUTF8String:title] :[NSString stringWithUTF8String:content]];
}

//通过返回值去匹配具体机型 http://theiphonewiki.com/wiki/Models
NSString *GetModel()
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6S (A1633/A1688/A1691/A1700)";
    if ([platform isEqualToString:@"iPhone8,8"]) return @"iPhone 6S Plus (A1634/A1687/A1690/A1699)";
     
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
     
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
     
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
     
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
     
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
     
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}
    
//获取当前设备可用内存(单位:MB)
int GetAvailableMemory()
{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(),
                                               HOST_VM_INFO,
                                               (host_info_t)&vmStats,
                                               &infoCount);
    
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    
    return (int)(((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0);
}

    
char* _MakeStringCopy( const char* string)
{
    if (NULL == string) {
        return NULL;
    }
    char* res = (char*)malloc(strlen(string)+1);
    strcpy(res, string);
    return res;
}
    
#if defined(__cplusplus)
}
#endif


@implementation CommonAppDelegate


// 显示提示框
-(void)showAlertView:(NSString *)btnTitle :(NSString *)content
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:content delegate:self cancelButtonTitle:btnTitle otherButtonTitles:nil];
    [alertView show];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) {
        // 选择确定后 在这里进行处理
        U3DSendMessage(ON_CLICK_RETRY, @"");
    }
}


//监测网络
-(void)ListenNetChange
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name: kReachabilityChangedNotificationA
                                               object: nil]; 
    hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
    [hostReach startNotifier];
}

//网络状态改变处理
- (void)reachabilityChanged:(NSNotification *)note
{
    NSLog(@"reachabilityChanged: 网络状态改变");
    U3DSendMessage(ON_CHANGE_NET_STATE, [hostReach GetNetState]);
}

-(void)UpdatePlayerInfo:(NSString *)info
{
    NSLog(@"CommonAppDelegate.UpdatePlayerInfo:%@", info);
}

-(void)GoAppStore
{
    NSLog(@"CommonAppDelegate.GoAppStore");
}

void UncaughtExceptionHandler(NSException *exception)
{
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    NSString *reason = [exception reason];//非常重要,就是崩溃的原因
    NSString *name = [exception name];//异常类型
    
    NSLog(@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr);
    
    exit(0);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"-----------------CommonAppDelegate.didFinishLaunchingWithOptions");
    [super application:application didFinishLaunchingWithOptions:launchOptions];
    
    application.applicationIconBadgeNumber = 0;
    appInstance = self;
    
    NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);

#ifndef NOSDK
    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            //categories
            [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)
             categories:nil];
            
        } else {
            //categories nil
            [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |  UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
#else
             //categories nil
             categories:nil];
            
            [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
#endif
             // Required
             categories:nil];
        }
    
    [APService setupWithOption:launchOptions];
#endif
    
    return YES;
}

#ifndef NOSDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // JPush Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // JPush Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    //JPush: IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
#endif

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    application.applicationIconBadgeNumber -= 1;
}

-(void)applicationDidEnterBackground:(UIApplication *)application
{
    [super applicationDidEnterBackground:application];
    if (application != nil) {
        ShieldPush(true);
    }
}

-(void)applicationWillEnterForeground:(UIApplication *)application
{
    [super applicationWillEnterForeground:application];
    if (application != nil) {
        ShieldPush(false);
        application.applicationIconBadgeNumber = 0;
    }
}

- (void)dealloc
{
    [hostReach dealloc];
    [super dealloc];
    appInstance = NULL;
}



ipv4/ipv6//




-(NSString *)CheckIpv4 : (NSDictionary *)dic
{
    if( [[dic allKeys]containsObject:@"en0/ipv6"])
    {
        NSString *ip=dic[@"en0/ipv6"];
        NSArray *array= [ip componentsSeparatedByString:@":"];
        if([[array objectAtIndex:0] isEqual:@"fe80"])
            return @"IPv4";
        else
            return @"IPv6";
    }
    else
        return @"IPv4";
    
}
- (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}
ipv4/ipv6//


@end




============================================================================================


/**
 * @date  2013-9-18 15:33:57
 * @author andy
 *
 */
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Security;
using Proto;
using System.Text.RegularExpressions;

namespace AssemblyCSharp
{
    class Connection : IConnection
    {
        public string connerctionName;
        public int bagMax = 30;  //每18ms要处理的最大消息数量
        public string server;
        public int port;

        //       private Thread thread;
        private ByteArrayBuffer buffer;
        private Socket socket = null;
        private List<byte[]> bagArray = new List<byte[]>();
        private System.Timers.Timer bagTimer = null;
        private int _serialNumber = 0; //消息号序列号
        //        private ProtobufSerializer serializer;
        private bool is_abort = false;

        /// <summary>
        ///  新建连接
        /// </summary>
        /// <param name="server">IP地址</param>
        /// <param name="port">端口号</param>
        /// <param name="name">本条连接唯一名字</param>
        public Connection(string server, int port, string name)
        {
            //            serializer = new ProtobufSerializer();
            buffer = new ByteArrayBuffer();
            this.setServerInfo(server, port);
            connerctionName = name;
        }

        private void setServerInfo(string server, int port)
        {
            if (server != null)
            {
                this.server = server;
            }
            if (port > 0)
            {
                this.port = port;
            }
        }

 
 
 


        public bool connect(string server, int port)
        {
            this.setServerInfo(server, port);



isIPv4 = SDKInfo.isIPv4;
if(!isIPv4)
server=FromIPv4ToIPv6(server);



            if (socket == null)
            {
if(isIPv4)
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
else
socket = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
            }
if(isIPv4)
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            if (socket.Connected == true)
            {
                return false;
            }
            // socket.Connect(new IPEndPoint(IPAddress.Parse(server), port));
            //服务器IP地址
            //IPAddress ipAddress = IPAddress.Parse(server);
            //服务器端口
            //IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, port);


IPAddress ipAddress; 
IPEndPoint ipEndpoint;
if (isIPv4) 
{
ipAddress = IPAddress.Parse(server);
ipEndpoint = new IPEndPoint(ipAddress, port);  
} else 
{
if(isIP)
{
ipAddress = IPAddress.Parse(server);
ipEndpoint = new IPEndPoint(ipAddress, port);
}
else
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(server); 
ipAddress = ipHostInfo.AddressList[0];
ipEndpoint = new IPEndPoint(ipAddress, port); 
}
}   



 
            IAsyncResult result;
            //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
            if (Application.platform == RuntimePlatform.WindowsWebPlayer)
            {
                result = socket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), socket);
                return false;
            }
            else
            {
                try
                {
#if UNITY_IPHONE
                    if (AutoUpdateUtil.Is64Bit)
                    {
                        result = socket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), socket);
                        return false;
                    }
#endif
                    result = socket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallbackLog), socket);
                }
                catch (System.ArgumentNullException e)
                {
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return false;
                }
                catch (System.Net.Sockets.SocketException e)
                {
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return false;
                }
                catch (System.ObjectDisposedException e)
                {
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return false;
                }
                catch (System.Security.SecurityException e)
                {
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return false;
                }
                catch (System.InvalidOperationException e)
                {
errorAlert(Lang.getValue("10001"));
// TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return false;
                }
            }

            bool success = false;
            try
            {
                //这里做一个超时的监测,当连接超过8秒还没成功表示超时
                success = result.AsyncWaitHandle.WaitOne(8000, true);
            }
            catch (SocketException e)
            {
                //DebugManager.Log("Failed to connect=>" + e);
            }

            if (socket == null || (socket != null && socket.Connected == false))
            {
errorAlert(Lang.getValue("10001"));
// TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
            }
            if (!success)
            {
                //DebugManager.Log("connect Time Out");
                //超时
                close();
            }
            else
            {
                //DebugManager.Log("else");
                /*          is_abort = false;
                          _serialNumber = 0;
                          MsgUtil.callFunc(connerctionName, null);
                          //与socket建立连接成功,开启线程接受服务端数据。
                          thread = new Thread(new ThreadStart(ReceiveSorket));
                          thread.IsBackground = true;
                          thread.Start();*/
                connectCallback(null);
            }

            return false;
        }

        public void reconnect()
        {
            if (socket == null || socket.Connected == true)
            {
                return;
            }
            //服务器IP地址
            IPAddress ipAddress = IPAddress.Parse(server);
            //服务器端口
            IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, port);
            //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
            IAsyncResult result = socket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), socket);
            //这里做一个超时的监测,当连接超过8秒还没成功表示超时
            /*           bool success = result.AsyncWaitHandle.WaitOne(8000, true);
                       if (!success)
                       {
                           //超时
                           close();
                           //DebugManager.Log("connect Time Out");
                       }
                       else
                       {
                           //与socket建立连接成功,开启线程接受服务端数据。
                           thread = new Thread(new ThreadStart(ReceiveSorket));
                           thread.IsBackground = true;
                           thread.Start();
                       }*/
        }

        private void connectCallbackLog(IAsyncResult asyncConnect)
        {
            //DebugManager.Log("connectCallbackLog");
        }

        private void connectCallback(IAsyncResult asyncConnect)
        {
            //           //DebugManager.Log("connectSuccess");
            //            OutLog.forceUpdate();
            is_abort = false;
            _serialNumber = 0;
            MsgUtil.callFunc(connerctionName, null);
            //            if (Application.platform == RuntimePlatform.WindowsWebPlayer)
            /*           {
                           thread = new Thread(new ThreadStart(ReceiveSorket));
                           thread.IsBackground = true;
                           thread.Start();
                       }*/
            /*           if (bagTimer == null)
                       {
                           bagTimer = new System.Timers.Timer(18);
                           bagTimer.Elapsed += new System.Timers.ElapsedEventHandler(onBagTimer);
                           bagTimer.AutoReset = true;
                           bagTimer.Enabled = true;
                       }
                       onBagTimer(null,null);*/
        }

        //       private void onBagTimer(object source, System.Timers.ElapsedEventArgs e)
        virtual public void onBagTimer()
        {
            ReceiveSorket();
            byte[] ba;
            for (int i = 0; i < bagMax; i++)
            {
                if (bagArray.Count == 0)
                {
                    break;
                }
                ba = bagArray[0] as byte[];
                bagArray.RemoveAt(0);
                handler(ba);
            }
        }

        protected void handler(byte[] ba)
        {
            ByteCode bc = decodeSocketByteArray(ba);
            if (bc == null)
            {
                return;
            }
            if (DebugConfig.isDebug && DebugConfig.msgFun != null)
                DebugConfig.msgFun(bc, "receive", BitConverter.ToString(ba));
            //string str = bc.getTypeId().ToString();
            MsgUtil.callFunc(bc.getTypeId().ToString(), bc);
            //string str = bc.getTypeId().ToString();
            showErrorMsg(bc);
        }


        private void showErrorMsg(ByteCode bc)
        {
            int errorCode = bc.getErrorCode();
            if (errorCode < 0 && !ErrorUtil.filterErrorCode.Contains(errorCode))
            {
                petUtils.isPlayingSoulEffect = false;
                if (errorCode == -1308 || errorCode == -1304)
                {
                    // 金钱不足 或者 元宝不足时,弹窗问询是否充值
                    MyAlert.cancelEnable = true;
                    MyAlert.OK_STR = LanUtil.getValue(101909);
                    MyAlert.CANCEL_STR = LanUtil.getValue(101910);
                    MyAlert.getInstance().showWindow(LanUtil.getValue(101908), ShowRechargeWindow, "");
                }
                else
                {
                    OperateAlert.getInstance().show(ErrorUtil.getValue(errorCode));
                    //DebugManager.Log("errorCode=>" + errorCode);
                }
            }
        }

        private void ShowRechargeWindow()
        {
            if (MainWinUtil.isOpenCharge)
            {
                //NewBieUtil.closeAllWin();
                AppFacade.getInstance().SendNotification(NotiConst.MENU_OPEN, new ModuleParam(ModuleParam.PAY_WINDOW));
            }
            else
            {
                OperateAlert.getInstance().show(LanUtil.getValue(105709));
            }
        }

        private ByteCode decodeSocketByteArray(byte[] ba)
        {
            if (ba == null || ba.Length <= 0)
            {
                return null;
            }
            ByteCode bc = new ByteCode(ba.Length - 8);
            byte[] temp = new byte[8];
            Array.Copy(ba, 0, temp, 0, 8);
            bc.setHead(temp);

            if (ba.Length > 8)
            {
                byte[] temp_body = new byte[ba.Length - 8];
                Array.Copy(ba, 8, temp_body, 0, ba.Length - 8);
                bc.setBody(temp_body);
            }
            return bc;
        }

        private void ReceiveSorket()
        {
            DebugManager.Log("ReceiveSorket thread id + " + Thread.CurrentThread.ManagedThreadId.ToString());
            //在这个线程中接受服务器返回的数据
            //           while (is_abort == false)
            {
                if (Application.platform != RuntimePlatform.WindowsWebPlayer)
                {
                    if (socket == null)
                    {
errorAlert(Lang.getValue("10001"));
// TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                        return;
                    }
                }
                if (!socket.Connected)
                {
                    //与服务器断开连接跳出循环
                    //DebugManager.Log("Failed to clientSocket server.");
errorAlert(Lang.getValue("10003"));
//TipDialog.Show(Lang.getValue("10003"), reLogin, null, Lang.getValue("10002"));
                    return;
                }
                try
                {
                    //接受数据保存至bytes当中
                    byte[] bytes = new byte[4096];
                    //Receive方法中会一直等待服务端回发消息
                    //如果没有回发会一直在这里等着。
                    if ((socket.Connected == false || socket.Available <= 0))
                    {
                        //   Thread.Sleep(133);
                        return;
                    }
                    int len = socket.Receive(bytes, 4096, SocketFlags.None);
                    if (len <= 0)
                    {
                        socket.Close();
                        return;
                    }
                    byte[] new_bytes = new byte[len];
                    Array.Copy(bytes, 0, new_bytes, 0, len);
                    buffer.pushByteArray(new_bytes);
                    //   //DebugManager.Log("返回的消息号:" + bytes);
                    List<byte[]> temp = buffer.split();
                    if (temp == null)
                    {
                        return;
                    }
                    bagArray.AddRange(temp);
                }
                catch (SocketException e_socket)
                {
                    //DebugManager.Log("socket exception" + e_socket.ErrorCode);
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return;
                }
                catch (ArgumentNullException e)
                {
                    //DebugManager.Log("Failed to clientSocket error." + e);
errorAlert(Lang.getValue("10001"));
// TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return;
                }
                catch (ObjectDisposedException e)
                {
                    //DebugManager.Log("ObjectDisposedException." + e);
errorAlert(Lang.getValue("10001"));
// TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return;
                }
                catch (SecurityException e)
                {
                    //DebugManager.Log("SecurityException." + e);
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                    return;
                }
            }
        }

        public void sendMsg<T>(T msg)
        {
            if (socket == null || !socket.Connected)
            {
errorAlert(Lang.getValue("10001"));
//TipDialog.Show(Lang.getValue("10001"), reLogin, null, Lang.getValue("10002"));
                return;
            }

            byte[] msg_byte = toSocketByteArrayMsg(msg, serialNumber());
            //向服务端异步发送这个字节数组
            /*         IAsyncResult asyncSend = socket.BeginSend(msg_byte, 0, msg_byte.Length, SocketFlags.None, new AsyncCallback(sendCallback), socket);
                        //监测超时
                        bool success = asyncSend.AsyncWaitHandle.WaitOne(5000, true);
                        if (!success)
                        {
                            socket.Close();
                            //DebugManager.Log("Time Out !");
                        }*/
            if (DebugConfig.isDebug && DebugConfig.msgFun != null)
                DebugConfig.msgFun(msg, "send", BitConverter.ToString(msg_byte));

            //        //DebugManager.Log("before-Send" + msg.GetType());
            //        OutLog.forceUpdate();

            try
            {
                socket.Send(msg_byte, 0, msg_byte.Length, SocketFlags.None);
                //             //DebugManager.Log("end-Send" + msg.GetType());
                //             OutLog.forceUpdate();
            }
            catch (SocketException e)
            {
errorAlert(Lang.getValue("10003"));
// TipDialog.Show(Lang.getValue("10003"), reLogin, null, Lang.getValue("10002"));
                //DebugManager.Log("send message error: " + e);
            }
            catch (ArgumentNullException e)
            {
errorAlert(Lang.getValue("10003"));
                //TipDialog.Show(Lang.getValue("10003"), reLogin, null, Lang.getValue("10002"));
                //DebugManager.Log("send message error: " + e);
            }
            catch (ArgumentOutOfRangeException e)
            {
errorAlert(Lang.getValue("10003"));
//TipDialog.Show(Lang.getValue("10003"), reLogin, null, Lang.getValue("10002"));
                //DebugManager.Log("send message error: " + e);
            }
            catch (ObjectDisposedException e)
            {
errorAlert(Lang.getValue("10003"));
//TipDialog.Show(Lang.getValue("10003"), reLogin, null, Lang.getValue("10002"));
                //DebugManager.Log("send message error: " + e);
            }
        }

        private void errorAlert(string msg)
{
if(connerctionName == "chatConnection"){
close();
if(ChatProxy.instances != null)
ChatProxy.instances.disconnect();
return;
}
TipDialog.Show(msg, reLogin, null, Lang.getValue("10002"));
            close();
            FrameTimerManager.getInstance().dispose();
            FrameTimerManager.getTimer().dispose();
            FrameTimerManager.getTimer("audioManager").dispose();
            MsgUtil.removeAllEventListener();
        }

        private void reLogin()
        {
            FrameTimerManager.getInstance().dispose();
            FrameTimerManager.getTimer().dispose();
            FrameTimerManager.getTimer("audioManager").dispose();
            FrameTimerManager.clear();
            TimeManager.dispose();
            MsgUtil.removeAllEventListener();
            if (GlobalVar.gameWorld != null)
            {
                GlobalVar.gameWorld.destroy();
            }
            Application.LoadLevel("GameLogin");
        }

        protected byte[] toSocketByteArrayMsg<T>(T msg, int seq)
        {

            byte[] body;

            if (msg is BaseCmd)
            {
                byte[] ba = new byte[16];
                Array.Copy(BitConverter.GetBytes(12), 0, ba, 0, 4);   //总长度
                Array.Copy(BitConverter.GetBytes(seq), 0, ba, 4, 4);    //序列号
                int msg_name = (msg as ICmd).getTypeId();
                Array.Copy(BitConverter.GetBytes(msg_name), 0, ba, 8, 4);    //消息号
                Array.Copy(BitConverter.GetBytes(0), 0, ba, 12, 4);    //预留
                return ba;
            }
            else
            {
                try
                {
                    body = ProtobufNet.Serialize(msg as ProtoMessage);
                    while (body == null)
                    {
                        body = ProtobufNet.Serialize(msg as ProtoMessage);
                    }
                    byte[] ba = new byte[16 + body.Length];
                    Array.Copy(BitConverter.GetBytes(body.Length + 12), 0, ba, 0, 4);   //总长度
                    Array.Copy(BitConverter.GetBytes(seq), 0, ba, 4, 4);    //序列号
                    int msg_name = int.Parse(msg.ToString().Substring(11, msg.ToString().Length - 11));
                    Array.Copy(BitConverter.GetBytes(msg_name), 0, ba, 8, 4);    //消息号
                    Array.Copy(BitConverter.GetBytes(0), 0, ba, 12, 4);    //预留
                    Array.Copy(body, 0, ba, 16, body.Length);    //body
                    return ba;
                }
                catch (Exception e)
                {
errorAlert(Lang.getValue("10003"));
//TipDialog.Show(Lang.getValue("10003"), reLogin, null, Lang.getValue("10002"));
                }

                return null;
            }

            //          //DebugManager.Log("end-serializer" + msg.GetType());
            //          OutLog.forceUpdate();


        }

        private void sendCallback(IAsyncResult asyncSend)
        {
        }

        protected int serialNumber()
        {
            return _serialNumber++;
        }

        public bool isConnect()
        {
            return (socket != null && socket.Connected);
        }

        //关闭Socket
        virtual public void close()
        {
            DebugManager.Log ("begin to close socket......");
            buffer.clear();
            /*        if (thread != null && Application.platform != RuntimePlatform.WindowsWebPlayer)
                    {
                        try
                        {
                    // thread.Abort();
                            is_abort = true;
                            thread.Join();
                            thread = null;
                        }
                        catch (ThreadStateException e)
                        {
                            //DebugManager.Log("关闭出错:"+e);
                        }

                    }*/
            if (socket != null && socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
                if (socket.Connected)
                {
                    socket.Close();
                }
            }
            socket = null;
            DebugManager.Log ("end close socket......");
        }



public bool isIP=true;
public bool isIPv4 = true;
private string FromDecimalToHexa(string strTen)
{
Debug.Log ("=========" + strTen);  
int intTen;
intTen = Convert.ToInt32(strTen);
string strHexa = Convert.ToString(intTen, 16);
if (strHexa.Length <= 1)
strHexa = "0" + strHexa;
return strHexa;
}
private string FromIPv4ToIPv6(string ipv4)
{
//23409:234523:345 ipv6
//235.34.2.3        ipv6
//center.sek.se.fk   ipv6
if(ipv4.Contains(":"))
return ipv4;
string ipv6;
string[] ip = ipv4.Split('.');
Debug.Log ("isNumber" + isNumber (ip));
if (!isNumber (ip)) {
isIP=false;
return ipv4;
}
Debug.Log ("=========" + ipv4);
ipv6 = string.Format("64:ff9b::{0}{1}:{2}{3}", FromDecimalToHexa(ip[0]), FromDecimalToHexa(ip[1]), FromDecimalToHexa(ip[2]), FromDecimalToHexa(ip[3]));
return ipv6;  
}
private bool isNumber(string[] ips)
{
for(int i=0;i<ips.Length;i++)
{
if(Regex.Matches(ips[i],"[a-zA-X]").Count!=0)
return false;
}  
return true;
}




    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值