用c#开发苹果应用程序xamarin.ios方式

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

NetworkComms网络通信框架序言

Networkcomms网络通信框架来自于英国,支持以xamarin.ios的方式开发苹果应用程序

其开源版本2.3.1中带有一个示例程序,实现聊天功能,只要输入对方手机的ip和端口就能够显示聊天,可以作为学习networkcomms框架的入门程序

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingMonoTouch.Foundation;usingMonoTouch.UIKit;usingNetworkCommsDotNet;namespaceExamplesChat.iOS

{//The UIapplicationDelegate for the application. This class is responsible for launching the//User Interface of the application, as well as listening (and optionally responding) to//application events from iOS.[Register("AppDelegate")]publicpartialclassAppDelegate : UIApplicationDelegate

{//class-level declarationspublicoverrideUIWindow Window

{get;set;

}///<summary>///If the application is minimised we need to correctly shutdown NetworkComms.Net///</summary>///<param name="application"></param>publicoverridevoidDidEnterBackground(UIApplication application)

{

NetworkComms.Shutdown();

}

}

}

AppDelegate.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingNetworkCommsDotNet;usingDPSBase;namespaceExamplesChat.iOS

{///<summary>///In an attempt to keep things as clear as possible all shared implementation across chat examples///has beenPRovided in this base class.///</summary>publicabstractclassChatAppBase

{#regionPrivate Fields///<summary>///A boolean used to track the very first initialisation///</summary>protectedboolFirstInitialisation {get;set; }///<summary>///Dictionary to keep track of which peer messages have already been written to the chat window///</summary>protectedDictionary<ShortGuid, ChatMessage> lastPeerMessageDict =newDictionary<ShortGuid, ChatMessage>();///<summary>///The maximum number of times a chat message will be relayed///</summary>intrelayMaximum =3;///<summary>///A local counter used to track the number of messages sent from///this instance.///</summary>longmessageSendIndex =0;///<summary>///An optional encryption key to use should one be required.///This can be changed freely but must obviously be the same///for both sender and reciever.///</summary>string_encryptionKey ="ljlhjf8uyfln23490jf;m21-=scm20--iflmk;";#endregion#regionPublic Fields///<summary>///The type of connection currently used to send and recieve messages. Default is TCP.///</summary>publicConnectionType ConnectionType {get;set; }///<summary>///The IP address of the server///</summary>publicstringServerIPAddress {get;set; }///<summary>///The port of the server///</summary>publicintServerPort {get;set; }///<summary>///The local name used when sending messages///</summary>publicstringLocalName {get;set; }///<summary>///A boolean used to track if the local device is acting as a server///</summary>publicboolLocalServerEnabled {get;set; }///<summary>///A boolean used to track if encryption is currently being used///</summary>publicboolEncryptionEnabled {get;set; }#endregion///<summary>///Constructor for ChatAppBase///</summary>publicChatAppBase(stringname, ConnectionType connectionType)

{

LocalName=name;

ConnectionType=connectionType;//Initialise the default valuesServerIPAddress ="";

ServerPort=10000;

LocalServerEnabled=false;

EncryptionEnabled=false;

FirstInitialisation=true;

}#regionNetworkComms.Net Methods///<summary>///Updates the configuration of this instance depending on set fields///</summary>publicvoidRefreshNetworkCommsConfiguration()

{#regionFirst Initialisation//On first initilisation we need to configure NetworkComms.Net to handle our incoming packet types//We only need to add the packet handlers once. If we call NetworkComms.Shutdown() at some future point these are not removed.if(FirstInitialisation)

{

FirstInitialisation=false;//Configure NetworkComms.Net to handle any incoming packet of type 'ChatMessage'//e.g. If we recieve a packet of type 'ChatMessage' execute the method 'HandleIncomingChatMessage'NetworkComms.AppendGlobalIncomingPacketHandler<ChatMessage>("ChatMessage", HandleIncomingChatMessage);//Configure NetworkComms.Net to perform some action when a connection is closed//e.g. When a connection is closed execute the method 'HandleConnectionClosed'NetworkComms.AppendGlobalConnectionCloseHandler(HandleConnectionClosed);

}#endregion#regionOptional Encryption//Configure encryption if requestedif(EncryptionEnabled && !NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSBase.DPSManager.GetDataProcessor<DPSBase.RijndaelPSKEncrypter>()))

{//Encryption is currently implemented using a pre-shared key (PSK) system//NetworkComms.Net supports multiple data processors which can be used with any level of granularity//To enable encryption globally (i.e. for all connections) we first add the encryption passWordas an optionDPSBase.RijndaelPSKEncrypter.AddPasswordToOptions(NetworkComms.DefaultSendReceiveOptions.Options, _encryptionKey);//Finally we add the RijndaelPSKEncrypter data processor to the sendReceiveOptionsNetworkComms.DefaultSendReceiveOptions.DataProcessors.Add(DPSBase.DPSManager.GetDataProcessor<DPSBase.RijndaelPSKEncrypter>());

}elseif(!EncryptionEnabled && NetworkComms.DefaultSendReceiveOptions.DataProcessors.Contains(DPSBase.DPSManager.GetDataProcessor<DPSBase.RijndaelPSKEncrypter>()))

{//If encryption has been disabled but is currently enabled//To disable encryption we just remove the RijndaelPSKEncrypter data processor from the sendReceiveOptionsNetworkComms.DefaultSendReceiveOptions.DataProcessors.Remove(DPSBase.DPSManager.GetDataProcessor<DPSBase.RijndaelPSKEncrypter>());

}#endregion#regionLocal Server Mode and Connection Type Changesif(LocalServerEnabled && ConnectionType == ConnectionType.TCP && !TCPConnection.Listening())

{//If we were previously listening for UDP we first shutdown comms.if(UDPConnection.Listening())

{

AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed.");

NetworkComms.Shutdown();

}else{

AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed.");

NetworkComms.Shutdown();

}//Start listening for new incoming TCP connections//Parameter is true so that we listen on a random port if the default is not availableTCPConnection.StartListening(true);//Write the IP addresses and ports that we are listening on to the chatBoxAppendLineToChatHistory("Listening for incoming TCP connections on:");foreach(varlistenEndPointinTCPConnection.ExistingLocalListenEndPoints())

AppendLineToChatHistory(listenEndPoint.Address+":"+listenEndPoint.Port);//Add a blank line after the initialisation outputAppendLineToChatHistory(System.Environment.NewLine);

}elseif(LocalServerEnabled && ConnectionType == ConnectionType.UDP && !UDPConnection.Listening())

{//If we were previously listening for TCP we first shutdown comms.if(TCPConnection.Listening())

{

AppendLineToChatHistory("Connection mode has been changed. Any existing connections will be closed.");

NetworkComms.Shutdown();

}else{

AppendLineToChatHistory("Enabling local server mode. Any existing connections will be closed.");

NetworkComms.Shutdown();

}//Start listening for new incoming UDP connections//Parameter is true so that we listen on a random port if the default is not availableUDPConnection.StartListening(true);//Write the IP addresses and ports that we are listening on to the chatBoxAppendLineToChatHistory("Listening for incoming UDP connections on:");foreach(varlistenEndPointinUDPConnection.ExistingLocalListenEndPoints())

AppendLineToChatHistory(listenEndPoint.Address+":"+listenEndPoint.Port);//Add a blank line after the initialisation outputAppendLineToChatHistory(System.Environment.NewLine);

}elseif(!LocalServerEnabled && (TCPConnection.Listening() ||UDPConnection.Listening()))

{//If the local server mode has been disabled but we are still listening we need to stop accepting incoming connectionsNetworkComms.Shutdown();

AppendLineToChatHistory("Local server mode disabled. Any existing connections will be closed.");

AppendLineToChatHistory(System.Environment.NewLine);

}elseif(!LocalServerEnabled &&((ConnectionType== ConnectionType.UDP && NetworkComms.GetExistingConnection(ConnectionType.TCP).Count >0) ||(ConnectionType== ConnectionType.TCP && NetworkComms.GetExistingConnection(ConnectionType.UDP).Count >0)))

{//If we are not running a local server but have changed the connection type after creating connections we need to close//existing connections.NetworkComms.Shutdown();

AppendLineToChatHistory("Connection mode has been changed. Existing connections will be closed.");

AppendLineToChatHistory(System.Environment.NewLine);

}#endregion}///<summary>///Performs whatever functions we might so desire when we recieve an incoming ChatMessage///</summary>///<param name="header">The PacketHeader corresponding with the recieved object</param>///<param name="connection">The Connection from which this object was recieved</param>///<param name="incomingMessage">The incoming ChatMessage we are after</param>protectedvirtualvoidHandleIncomingChatMessage(PacketHeader header, Connection connection, ChatMessage incomingMessage)

{//We only want to write a message once to the chat window//Because we support relaying and may recieve the same message twice from multiple sources//we use our history and message indexes to ensure we have a new message//We perform this action within a lock as HandleIncomingChatMessage could be called in parallellock(lastPeerMessageDict)

{if(lastPeerMessageDict.ContainsKey(incomingMessage.SourceIdentifier))

{if(lastPeerMessageDict[incomingMessage.SourceIdentifier].MessageIndex <incomingMessage.MessageIndex)

{//If this message index is greater than the last seen from this source we can safely//write the message to the ChatBoxAppendLineToChatHistory(incomingMessage.SourceName +"-"+incomingMessage.Message);//We now replace the last recieved message with the current onelastPeerMessageDict[incomingMessage.SourceIdentifier] =incomingMessage;

}

}else{//If we have never had a message from this source before then it has to be new//by defintionlastPeerMessageDict.Add(incomingMessage.SourceIdentifier, incomingMessage);

AppendLineToChatHistory(incomingMessage.SourceName+"-"+incomingMessage.Message);

}

}//This last section of the method is the relay feature//We start by checking to see if this message has already been relayed the maximum number of timesif(incomingMessage.RelayCount <relayMaximum)

{//If we are going to relay this message we need an array of//all known connections, excluding the current onevarallRelayConnections = (fromcurrentinNetworkComms.GetExistingConnection()wherecurrent != connectionselectcurrent).ToArray();//We increment the relay count before we sendincomingMessage.IncrementRelayCount();//We now send the message to every other connectionforeach(varrelayConnectioninallRelayConnections)

{//We ensure we perform the send within a try catch//To ensure a single failed send will not prevent the//relay to all working connections.try{ relayConnection.SendObject("ChatMessage", incomingMessage); }catch(CommsException) {/*Catch the comms exception, ignore and continue*/}

}

}

}///<summary>///Performs whatever functions we might so desire when an existing connection is closed.///</summary>///<param name="connection">The closed connection</param>privatevoidHandleConnectionClosed(Connection connection)

{//We are going to write a message to the chat history when a connection disconnects//We perform the following within a lock incase mutliple connections disconnect simultaneouslylock(lastPeerMessageDict)

{//Get the remoteIdentifier from the closed connection//This a unique GUID which can be used to identify peersShortGuid remoteIdentifier =connection.ConnectionInfo.NetworkIdentifier;//If at any point we recieved a message with a matching identifier we can//include the peer name in the disconnection message.if(lastPeerMessageDict.ContainsKey(remoteIdentifier))

AppendLineToChatHistory("Connection with '"+ lastPeerMessageDict[remoteIdentifier].SourceName +"' has been closed.");elseAppendLineToChatHistory("Connection with '"+ connection.ToString() +"' has been closed.");//Last thing is to remove this peer from our message historylastPeerMessageDict.Remove(connection.ConnectionInfo.NetworkIdentifier);

}

}///<summary>///Send a message.///</summary>publicvoidSendMessage(stringstringToSend)

{//If we have tried to send a zero length string we just returnif(stringToSend.Trim() =="")return;//We may or may not have entered some server connection informationConnectionInfo serverConnectionInfo =null;if(ServerIPAddress !="")

{try{ serverConnectionInfo =newConnectionInfo(ServerIPAddress, ServerPort); }catch(Exception)

{

ShowMessage("Failed to parse the server IP and port. Please ensure it is correct and try again");return;

}

}//We wrap everything we want to send in the ChatMessage class we createdChatMessage chatMessage =newChatMessage(NetworkComms.NetworkIdentifier, LocalName, stringToSend, messageSendIndex++);//We add our own message to the message history incase it gets relayed back to uslock(lastPeerMessageDict) lastPeerMessageDict[NetworkComms.NetworkIdentifier] =chatMessage;//We write our own message to the chatBoxAppendLineToChatHistory(chatMessage.SourceName +"-"+chatMessage.Message);//Clear the input box textClearInputLine();//If we provided server information we send to the server firstif(serverConnectionInfo !=null)

{//We perform the send within a try catch to ensure the application continues to run if there is a problem.try{if(ConnectionType ==ConnectionType.TCP)

TCPConnection.GetConnection(serverConnectionInfo).SendObject("ChatMessage", chatMessage);elseif(ConnectionType ==ConnectionType.UDP)

UDPConnection.GetConnection(serverConnectionInfo, UDPOptions.None).SendObject("ChatMessage", chatMessage);elsethrownewException("An invalid connectionType is set.");

}catch(CommsException) { AppendLineToChatHistory("Error: A communication error occured while trying to send message to"+ serverConnectionInfo +". Please check settings and try again."); }catch(Exception) { AppendLineToChatHistory("Error: A general error occured while trying to send message to"+ serverConnectionInfo +". Please check settings and try again."); }

}//If we have any other connections we now send the message to those as well//This ensures that if we are the server everyone who is connected to us gets our message//We want a list of all established connections not including the server if setList<ConnectionInfo>otherConnectionInfos;if(serverConnectionInfo !=null)

otherConnectionInfos= (fromcurrentinNetworkComms.AllConnectionInfo()wherecurrent.RemoteEndPoint != serverConnectionInfo.RemoteEndPointselectcurrent).ToList();elseotherConnectionInfos=NetworkComms.AllConnectionInfo();foreach(ConnectionInfo infoinotherConnectionInfos)

{//We perform the send within a try catch to ensure the application continues to run if there is a problem.try{if(ConnectionType ==ConnectionType.TCP)

TCPConnection.GetConnection(info).SendObject("ChatMessage", chatMessage);elseif(ConnectionType ==ConnectionType.UDP)

UDPConnection.GetConnection(info, UDPOptions.None).SendObject("ChatMessage", chatMessage);elsethrownewException("An invalid connectionType is set.");

}catch(CommsException) { AppendLineToChatHistory("Error: A communication error occured while trying to send message to"+ info +". Please check settings and try again."); }catch(Exception) { AppendLineToChatHistory("Error: A general error occured while trying to send message to"+ info +". Please check settings and try again."); }

}return;

}#endregion#regionGUI Interface Methods///<summary>///Outputs the usage instructions to the chat window///</summary>publicvoidPrintUsageInstructions()

{

AppendLineToChatHistory("");

AppendLineToChatHistory("Chat usage instructions:");

AppendLineToChatHistory("");

AppendLineToChatHistory("Step 1. Open atleast two chat applications. You can choose from Android, Windows Phone, iOS or native Windows versions.");

AppendLineToChatHistory("Step 2. Enable local server mode in a single application, see settings.");

AppendLineToChatHistory("Step 3. Provide remote server IP and port information in settings on remaining application.");

AppendLineToChatHistory("Step 4. Start chatting.");

AppendLineToChatHistory("");

AppendLineToChatHistory("Note: Connections are established on the first message send.");

AppendLineToChatHistory("");

}///<summary>///Append the provided message to the chat history text box.///</summary>///<param name="message">Message to be appended</param>publicabstractvoidAppendLineToChatHistory(stringmessage);///<summary>///Clears the chat history///</summary>publicabstractvoidClearChatHistory();///<summary>///Clears the input text box///</summary>publicabstractvoidClearInputLine();///<summary>///Show a message box as an alternative to writing to the chat history///</summary>///<param name="message">Message to be output</param>publicabstractvoidShowMessage(stringmessage);#endregion}

}

ChatAppBase

usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingMonoTouch.Foundation;usingMonoTouch.UIKit;usingNetworkCommsDotNet;namespaceExamplesChat.iOS

{///<summary>///All NetworkComms.Net implementation can be found here and in ChatAppBase///</summary>publicclassChatAppiOS : ChatAppBase

{#regionPublic Fields///<summary>///Size of the chat history view when the keyboard is hidden///</summary>publicreadonlyRectangleF OriginalViewSize =newRectangleF(0,0,320,416);///<summary>///Reference to the chatHistory text view.///</summary>publicUITextView ChatHistoryBox {get;privateset; }///<summary>///Reference to the message box.///</summary>publicUITextField MessageBox {get;privateset; }#endregion///<summary>///Constructor for the iOS chat app.///</summary>publicChatAppiOS(UITextView chatHistoryBox, UITextField messageBox)

:base("iPhone", ConnectionType.TCP)

{

ChatHistoryBox=chatHistoryBox;

MessageBox=messageBox;

}#regionGUI Interface OverridespublicoverridevoidAppendLineToChatHistory(stringmessage)

{

ChatHistoryBox.InvokeOnMainThread(newNSAction(() =>{

ChatHistoryBox.Text+= message +Environment.NewLine;

PointF bottomOffset=newPointF(0, ChatHistoryBox.ContentSize.Height -ChatHistoryBox.Bounds.Size.Height);

ChatHistoryBox.SetContentOffset(bottomOffset,true);

}));

}publicoverridevoidClearChatHistory()

{

ChatHistoryBox.InvokeOnMainThread(newNSAction(() =>{

ChatHistoryBox.Text="";

PointF bottomOffset=newPointF(0, ChatHistoryBox.ContentSize.Height -ChatHistoryBox.Bounds.Size.Height);

ChatHistoryBox.SetContentOffset(bottomOffset,true);

}));

}publicoverridevoidClearInputLine()

{

MessageBox.InvokeOnMainThread(newNSAction(() =>{

MessageBox.Text="";

}));

}publicoverridevoidShowMessage(stringmessage)

{thrownewNotImplementedException();

}#endregion}

}

ChatAppiOS

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;//We need to add the following two namespaces to this classusingNetworkCommsDotNet;usingProtoBuf;namespaceExamplesChat.iOS

{///<summary>///A wrapper class for the messages that we intend to send and recieve.///The [ProtoContract] attribute informs NetworkCommsDotNet that we intend to///serialise (turn into bytes) this object. At the base level the///serialisation is performed by protobuf.net.///</summary>[ProtoContract]publicclassChatMessage

{///<summary>///The source identifier of this ChatMessage.///We use this variable as the constructor for the ShortGuid.///The [ProtoMember(1)] attribute informs the serialiser that when///an object of type ChatMessage is serialised we want to include this variable///</summary>[ProtoMember(1)]string_sourceIdentifier;///<summary>///The source identifier isaccessible as a ShortGuid///</summary>publicShortGuid SourceIdentifier {get{returnnewShortGuid(_sourceIdentifier); } }///<summary>///The name of the source of this ChatMessage.///We use shorthand declaration, get and set.///The [ProtoMember(2)] attribute informs the serialiser that when///an object of type ChatMessage is serialised we want to include this variable///</summary>[ProtoMember(2)]publicstringSourceName {get;privateset; }///<summary>///The actual message.///</summary>[ProtoMember(3)]publicstringMessage {get;privateset; }///<summary>///The index of this message. Every message sent by a particular source///has an incrementing index.///</summary>[ProtoMember(4)]publiclongMessageIndex {get;privateset; }///<summary>///The number of times this message has been relayed.///</summary>[ProtoMember(5)]publicintRelayCount {get;privateset; }///<summary>///We must include a public parameterless constructor to be used by the deserialisation step.///</summary>publicChatMessage() { }///<summary>///Create a new ChatMessage///</summary>///<param name="sourceIdentifier">The source identifier</param>///<param name="sourceName">The source name</param>///<param name="message">The message to be sent</param>///<param name="messageIndex">The index of this message</param>publicChatMessage(ShortGuid sourceIdentifier,stringsourceName,stringmessage,longmessageIndex)

{this._sourceIdentifier =sourceIdentifier;this.SourceName =sourceName;this.Message =message;this.MessageIndex =messageIndex;this.RelayCount =0;

}///<summary>///Increment the relay count variable///</summary>publicvoidIncrementRelayCount()

{

RelayCount++;

}

}

}

ChatMessage

//This file has been autogenerated from parsing an Objective-C header file added in Xcode.usingSystem;usingSystem.Linq;usingSystem.Net;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.IO;usingMonoTouch.Foundation;usingMonoTouch.UIKit;usingNetworkCommsDotNet;usingDPSBase;namespaceExamplesChat.iOS

{publicpartialclassChatWindow : UIViewController

{publicstaticChatAppiOS ChatApplication {get;set; }publicChatWindow (IntPtr handle) :base(handle)

{

}///<summary>///On load initialise the example///</summary>publicoverridevoidViewDidLoad()

{base.ViewDidLoad();//Subscribe to the keyboard eventsNSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidHideNotification, HandleKeyboardDidHide);

NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, HandleKeyboardDidShow);//Remove the keyboard if the screen is tappedvartap =newUITapGestureRecognizer();

tap.AddTarget(()=>{this.View.EndEditing(true);

});this.View.AddGestureRecognizer(tap);//Create the chat application instanceChatApplication =newChatAppiOS(ChatHistory, MessageBox);//Uncomment this line to enable logging//EnableLogging();//Print out the application usage instructionsChatApplication.PrintUsageInstructions();//Initialise comms to add the neccessary packet handlersChatApplication.RefreshNetworkCommsConfiguration();

}///<summary>///Enable logging, usefull for debugging applications.///</summary>privatevoidEnableLogging()

{//We will create the log file in the local documents directorystringlogFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),"NetworkCommsLog.txt");

ChatApplication.AppendLineToChatHistory("Logging enabled to"+logFileName);

NetworkComms.EnableLogging(logFileName);

}#regionEvent Handlers///<summary>///Sends the message when send button is clicked///</summary>///<param name="sender"></param>partialvoidSendButtonClick(NSObject sender)

{

ChatApplication.SendMessage(MessageBox.Text);

}///<summary>///Resize the view to take into account the keyboard position///</summary>///<param name="notification"></param>voidHandleKeyboardDidShow(NSNotification notification)

{

ChatApplication.ClearInputLine();

NSObject value=notification.UserInfo[UIKeyboard.FrameEndUserInfoKey];

RectangleF keyboardFrame=((NSValue)value).RectangleFValue;

ChatView.Frame=newSystem.Drawing.RectangleF(ChatView.Frame.X, ChatView.Frame.Y, ChatView.Frame.Width, ChatView.Frame.Height -keyboardFrame.Height);

PointF bottomOffset=newPointF(0, ChatHistory.ContentSize.Height -ChatHistory.Bounds.Size.Height);

ChatHistory.SetContentOffset(bottomOffset,true);

}///<summary>///Resize the view once the keyboard has been minimised///</summary>///<param name="notification"></param>privatevoidHandleKeyboardDidHide(NSNotification notification)

{//Set back to original sizeChatView.Frame =ChatApplication.OriginalViewSize;

}#endregion}

}

ChatWindow

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingMonoTouch.Foundation;usingMonoTouch.UIKit;namespaceExamplesChat.iOS

{publicclassApplication

{//This is the main entry point of the application.staticvoidMain(string[] args)

{//if you want to use a different Application Delegate class from "AppDelegate"//you can specify it here.UIApplication.Main(args,null,"AppDelegate");

}

}

}

Application

//This file has been autogenerated from parsing an Objective-C header file added in Xcode.usingSystem;usingMonoTouch.Foundation;usingMonoTouch.UIKit;usingNetworkCommsDotNet;namespaceExamplesChat.iOS

{publicpartialclassSettings : UIViewController

{publicSettings (IntPtr handle) :base(handle)

{

}///<summary>///On load set the config as per the chat application///</summary>publicoverridevoidViewDidLoad()

{base.ViewDidLoad();//Remove the keyboard on a tap gesturevartap =newUITapGestureRecognizer();

tap.AddTarget(()=>{this.View.EndEditing(true);

});this.View.AddGestureRecognizer(tap);//Get a reference to the chat applicationChatAppiOS chatApplication =ChatWindow.ChatApplication;//Update the settings based on previous valuesLocalServerEnabled.SetState(chatApplication.LocalServerEnabled,false);

MasterIP.Text=chatApplication.ServerIPAddress;

MasterPort.Text=chatApplication.ServerPort.ToString();

LocalName.Text=chatApplication.LocalName;

EncryptionEnabled.SetState(chatApplication.EncryptionEnabled,false);//Set the correct segment on the connection mode toggleConnectionMode.SelectedSegment = (chatApplication.ConnectionType == ConnectionType.TCP ?0:1);

}///<summary>///Update the settings when the user goes back to the main interface///</summary>///<returns></returns>publicoverrideboolResignFirstResponder()

{//Get a reference to the chat applicationChatAppiOS chatApplication =ChatWindow.ChatApplication;//Parse settings and store back in chat applicationchatApplication.ServerIPAddress =MasterIP.Text.Trim();intport =10000;int.TryParse(MasterPort.Text,outport);

chatApplication.ServerPort=port;

chatApplication.LocalName=LocalName.Text.Trim();

chatApplication.EncryptionEnabled=EncryptionEnabled.On;

chatApplication.LocalServerEnabled=LocalServerEnabled.On;if(ConnectionMode.SelectedSegment ==0)

chatApplication.ConnectionType=ConnectionType.TCP;elsechatApplication.ConnectionType=ConnectionType.UDP;//Refresh the NetworkComms.Net configuration once any changes have been madechatApplication.RefreshNetworkCommsConfiguration();returnbase.ResignFirstResponder();

}

}

}

Settings

工程文件下载地址 networkcomm2.3.1开源通信框架下载网页

www.networkcomms.cn

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航