IOS UDP broadcast as client

Serious explanation before major update

Jane book friend, contact me said long time no see I updated, this time is not busy, just feel a lot of things on the job, did not seem to share the essence of what (it seems to be a look normal excuse), serious face.Jpg.

Treatment of cancer

The company to do smart home, at the beginning of the WiFi is the device into the network, and then use WiFi or 4G to control the hardware device, but with WiFi, then the requirements of the network is extremely high. Due to the limitations of the three network operators, WiFi to a certain extent is not so good speed. So in the past few years, things began to look for a better agreement to control the hardware, the beginning of the socket is still very popular, so far still good. Now use the better is the mqtt agreement, because there are relatively few open source, small companies with this agreement or a small number of. Said so much, or return to the theme, directly in the LAN how to use UDP to send packets to the server, thus efficient and fast control equipment.

An encyclopedia of UDP is explained:

IOS UDP broadcast as client

in fact, UDP, written on the basis of the third party is very simple, because the bottom has been written, we only need to focus on their business logic can be. GitHub download more than the main CocoaAsyncSocket, he has a Runloop based on a GCD, we see their own needs. Here is GCD which based on the people according to the operation of GitHub, directly to the three parties into their own projects or can be imported by pods. I used in the project is
GCDAsyncUdpSocket.
I direct the following code:

#import < Foundation/Foundation.h> #import "GCDAsyncUdpSocket.h" @protocol UDPClientSocketDelegate < NSObject> - (void) clientSocketDidReceiveMessage: (NSString *) message andPort: (uint16_t) port withHost: (NSString * hostIP); @end @interface UDPClientSocket: NSObject < GCDAsyncUdpSocketDelegate> @property (nonatomic, assign) NSInteger times @property (nonatomic, weak); ID < UDPClientSocketDelegate> delegate; @property (nonatomic, strong) GCDAsyncUdpSocket * udpSocket (nonatomic, copy); @property NSString *mHost; @property (nonatomic, assign) int + mPort (UDPClientSocket *); shareInstance; - (void) getAddressAndPort: (NSString * hostID); - (void) sendMessageToHost: (NSString *) host WithPort: (uint16_t) port transData: (NSDictiona Ry * dataPackage; //-) (void) sendMessage: (NSString *) message - (void); disconnect; @end

Because in the host communication, as long as the state will send control equipment or query devices with UDP, so that in the.H file to write a proxy, can directly to the server to return the package to get directly in their own areas of need.

IOS UDP broadcast as client
UDP delegate.png

look at the following.M file:

#import "UDPClientSocket.h" @implementation + UDPClientSocket (UDPClientSocket *) shareInstance{static UDPClientSocket * clientUdp = nil; static dispatch_once_t onceToken; dispatch_once (& onceToken, clientUdp ^{= [[self alloc]init]; return clientUdp;}}); / / detect whether connected - (void) getAddressAndPort: (NSString *) hostID{NSString *url [NSString stringWithFormat:@ = "%@/host/GetHostLocation" (NSDictionary, getIP); *params = @{kSessionID:getMySessionID ("HostID"), @: hostID}; [SZRequest PostURLForNetRequest:url AndParams:params block:^ (ID result) {NSLog (@ host IP:%@, result); if (Kerrcode==0) {_mHost = result[@; _mPort = "HostIP" [result[@ "HostPort" int Value]; / / NSDictionary *params = @{@ probe packet "devID": @, @ requestCode @ @: "8900", "userName": [mUserDefaults objectForKey:UserName]}; [self sendMessageToHost:_mHost WithPort: (uint16_t) _mPort transData:params] [mUserDefaults setObject:_mHost forKey:KhostIP]; [mUserDefaults; setInteger:_mPort forKey:KhostPort]; [mUserDefaults synchronize];}} andBlock:^ (NSError *error) {NSLog (@ error =% @ ", error);}];} - (void) sendMessageToHost: (NSString *) host WithPort: (uint16_t) port transData: (NSDictionary *) dataPackage{dispatch_queue_t dispatch_get_global_queue (queue = DISPATCH_QUEUE_PRIORITY_DEFAULT, self.udpSocket = 0); [[GCDAsyncUdpSocket a Lloc]initWithDelegate:self delegateQueue:queue]; NSLog (@ dataPackage, data=%@% @%d, host, port); NSData *data = [[CJSONDataSerializer serializer] serializeDictionary:dataPackage]; [self.udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0]; [self.udpSocket receiveOnce:nil];} //- (void) sendMessage: (NSString *) message{/ / NSData data = [message * dataUsingEncoding:NSUTF8StringEncoding]; / / [self.udpSocket sendData:data toHost:@ 192.168.7.113 port:8011 withTimeout:-1 tag:0]; //} - (void) disconnect{[self.udpSocket closeAfterSending];} - (void) udpSocket: (GCDAsyncUdpSocket * sock) didReceiveData: (NSData * data) fromAddress: (NSData *) address withFilterContext: (ID) filterContext{NSString * IP = [GCD AsyncUdpSocket hostFromAddress:address]; uint16_t port = [GCDAsyncUdpSocket portFromAddress:address]; NSString * message = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog (@ "received to the server: ip:%@ port:%d message:%@, IP, port, message); if ([self.delegate respondsToSelector:@selector (clientSocketDidReceiveMessage:andPort:withHost:)] [self.delegate clientSocketDidReceiveMessage:message andPort:port) {withHost:ip]}; [self.udpSocket receiveOnce:nil]; [self.udpSocket / beginReceiving:nil];}

First + (UDPClientSocket *) shareInstance this, we all know this is a single case, because in the program are used in many places, in order to avoid redundant code to write more in other files, so a single case is very convenient.
/ / detect whether connected
(void) – getAddressAndPort: (NSString * hostID) this is here, because he is the needs of the project, each time to send control requests, should be the first to detect that he is not the host and how the same LAN, if it is to receive packets in the same LAN so, can the local control host.
– (void) sendMessageToHost: (NSString) host WithPort: (uint16_t) port transData: (NSDictionary) dataPackage is the data packets sent to write their own methods, this method is called, need incoming server IP and server port, there is a need to pass the packet server. The reason why I came here in the dictionary, because I pass this data is the JSON string, and then the dictionary into NSData format, the server will be able to receive the data sent by my side. NSData *data = [[CJSONDataSerializer serializeDictionary:dataPackage]; this is NSDictionary to NSData, this method is also used in the third party library, but also very good looking for the.

IOS UDP broadcast as client
delegate.png

this proxy method is written in the receipt of the server back to the package, you can receive the data sent to their own call the proxy method of the class.

UDPClientSocket use

In their own use of the UDP class, the first import “UDPClientSocket.h” file, and then follow the UDPClientSocketDelegate, the proxy method written in, we can be very happy to use it.

IOS UDP broadcast as client
using.Png

follow-up will update a server, combined with their client, you can use the computer to do the server, mobile phone client, communication. Of course, I will continue to write this piece of business logic, and then write a summary.

Finally, I would like to see this article, a small partner to recommend some books that I feel good or great God blog or fun fun all.

Come on, play with the code!!!

Attached demo:
link: https://pan.baidu.com/s/1cvQPw6 password: jtu7
if you do not understand please leave a message ~ ~ ~ ~