TCP mobile interacts with server data

Source: Internet
Author: User
Tags sendmsg uikit

Client and server side under the same notebook

TCPClient Client:

RootViewController.h
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"//encapsulates socket programming based on TCP protocol
The TCP protocol is a protocol located at the network transport layer, which specifies how the client communicates with the server, or between the client and the client.
Each client or server is identified by IP address + port
/* Client-to-server data communication based on TCP protocol
* 1, the client needs to connect the specified server via the ip+ port
* 2, after the successful connection, the client can send data to the server
* 3, the server can receive data and follow-up processing
* 4, if the client disconnects from the server, the server can know
5, Asyncsocket the use of a folder directly dragged into the project, two. m files are set to-fno-objc-arc
*/
@interface Rootviewcontroller:uiviewcontroller
<AsyncSocketDelegate>

Rootviewcontroller.m
#import "RootViewController.h"

@interface Rootviewcontroller ()
{
Client socket for data communication with the server
Asyncsocket *_clientsocket;
}
@end

@implementation Rootviewcontroller

-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) Nibbundleornil
{
self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil];
if (self) {
Custom initialization
}
return self;
}

-(void) viewdidload
{
[Super Viewdidload];

UIButton *connectbtn = [UIButton buttonwithtype:uibuttontyperoundedrect];
[Connectbtn settitle:@ "Connect" forstate:uicontrolstatenormal];
[Connectbtn Setframe:cgrectmake (10,30,300,40)];
[Connectbtn addtarget:self Action: @selector (connectbtnclicked) forcontrolevents:uicontroleventtouchupinside];
[Self.view ADDSUBVIEW:CONNECTBTN];

UIButton *sendbtn = [UIButton buttonwithtype:uibuttontyperoundedrect];
[Sendbtn settitle:@ "send" forstate:uicontrolstatenormal];
[Sendbtn Setframe:cgrectmake (10,80,300,40)];
[Sendbtn addtarget:self Action: @selector (SendData) forcontrolevents:uicontroleventtouchupinside];
[Self.view ADDSUBVIEW:SENDBTN];

Do any additional setup after loading the view.
}
Send data to a server that has successfully connected
-(void) senddata{
NSString *sendmsg = @ "Hello server!";
NSData *data = [sendmsg datausingencoding:nsutf8stringencoding];
WriteData the data to be sent, 1 is not limited to send, tag is used to identify the current operation
[_clientsocket writedata:data withtimeout:-1 tag:0];
}

-(void) connectbtnclicked{
If the object does not exist, create the
if (!_clientsocket) {
Initializing and setting up the proxy
_clientsocket = [[Asyncsocket alloc] initwithdelegate:self];
}
IsConnected whether the server was contacted
if ([_clientsocket isconnected]) {
[_clientsocket disconnect];//if connected, disconnect
}
Connect to the specified server via the ip+ port
[_clientsocket connecttohost:<# (NSString *) #> onport:<# (UInt16) #> error:<# (Nserror *__ Autoreleasing *) #>]
The IP address is native, because the server is also built on the same computer

Port any four-bit number
Connecttohost and Onport are the IP addresses and ports of the server
-1 Unlimited time connections
[_clientsocket connecttohost:@ "own IP Address" onport:5678 withtimeout:-1 Error:nil];
}

#pragma mark-asyncsocket delegate
This method is called if the connection to the server is successful
-(void) Onsocket: (Asyncsocket *) sock didconnecttohost: (NSString *) host port: (UInt16) port{
NSLog (@ "did connected!");
}
The data is sent to completion, calling this method
-(void) Onsocket: (Asyncsocket *) sock Didwritedatawithtag: (long) tag{
NSLog (@ "Send data!");
}


TCPServer Server: Need to import asyncsocket third party

#import "AppDelegate.h"
@implementation appdelegate{
The server socket object that listens for client connection
Asyncsocket *_serversocket;
Used to store socket objects
Nsmutablearray *_socketarray;

}

-(void) applicationdidfinishlaunching: (nsnotification *) anotification
{
Insert code here to initialize your application
_socketarray = [[Nsmutablearray alloc] init];
Execute the Createserver method
Allow self to execute createserver after 0.2 seconds
[Self performselector: @selector (createserver) Withobject:nil afterdelay:0.2];

}
-(void) createserver{
Initialization
_serversocket = [[Asyncsocket alloc] initwithdelegate:self];
Listen to your own IP and port if a client is connected
[_serversocket acceptoninterface:@ "own IP Address" port:5678 Error:nil];
IP address can be defaulted
[_serversocket acceptonport:5678 Error:nil];
}
#pragma mark-async Socket Delegate
This method is called once a client is connected
A socket object created by the Newsocket server for subsequent data interaction with the client
-(void) Onsocket: (Asyncsocket *) sock didacceptnewsocket: (Asyncsocket *) newsocket{
NSLog (@ "Accept socket!");
The Newsocket object needs to be stored, otherwise the object will be automatically freed.
[_socketarray Addobject:newsocket];
The Newsocket object is used to listen to whether a client that has been connected will send a message
Do you have any data sent over the time of unlimited monitoring?
[Newsocket readdatawithtimeout:-1 tag:100];
}
This method is triggered when the client's data is received
Data for the client
-(void) Onsocket: (Asyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag{
NSString *msg = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];
NSLog (@ "Receive data:%@", msg);
Once the data is received, the last listener fails and needs to continue listening.
[sock readdatawithtimeout:-1 tag:101];
}
This method is triggered when the client is about to disconnect from the server
-(void) Onsocket: (Asyncsocket *) sock willdisconnectwitherror: (Nserror *) err{
NSLog (@ "would disconnect!");
}
Already disconnected
-(void) Onsocketdiddisconnect: (Asyncsocket *) sock{
NSLog (@ "did disconnect!");
}

TCP mobile interacts with server data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.