当前位置:网站首页>Afnetworking server client
Afnetworking server client
2022-06-24 02:29:00 【User 7108768】
// Monitoring network status (AFNetworking)
import "ViewController.h"
// Introduce a third-party framework
import "AFNetworking/AFNetworking.h"
@interface ViewController ()
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad];
// Check network status
[self checkNetworkStates];
}
#pragma mark Check network status
-(void)checkNetworkStates{
//1. We created a for testing url
NSURL url = [NSURL URLWithString:@"http://www.apple.com"];
//2. Establish an operation management
AFHTTPRequestOperationManager operationManager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:url];
//3. According to different network states , Go and deal with it
[operationManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(@" Network not found ");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@" adopt wifi Connect ");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@" adopt 2G/3G/4G Connect ");
break;
case AFNetworkReachabilityStatusUnknown:
NSLog(@" Unknown ");
break;
default:
break;
}
}];
// Start monitoring ( Monitor the changes of network status in real time )
[operationManager.reachabilityManager startMonitoring];
}
// Server side
import <Foundation/Foundation.h>
include<sys/socket.h>// Provide socket Functions and data structures
include<netinet/in.h>// Define the data structure
include <arpa/inet.h>// Provide IP Address translation function
int main() {
// Server order : socket->bind->listen->while(true) accept -> do while recv ->close
int fd = socket(AF_INET, SOCK_STREAM, 0);// The protocol does not call
BOOL success = (fd != -1);
struct sockaddr_in addr;// Represents the server
int err;
// Server address setting
if(success){
NSLog(@"socket success ");
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(1024);
addr.sin_addr.s_addr = INADDR_ANY;
// Binding
err = bind(fd, (const struct sockaddr )&addr, sizeof(addr));
success = (err == 0);
}
if(success){
NSLog(@"bind success ");
//listen monitor
// The second parameter is the size of the queue waiting to receive connections . For example connect When you ask to come , After three handshakes, put the connection in the queue , Until it is accept Handle . If the queue is full , And when there are new connections , The other party may receive an error message ( In fact, it is a process of queuing , And the process of collection )
err = listen(fd,5);
success = (err == 0);
}
if(success){
NSLog(@"listen success ");
while(true){
struct sockaddr_in clientaddr;
// Define a client socket , Socket used to get the received client
int clientfd;
// Define an address length variable , Length of receiving client
socklen_t addrLen;
addrLen = sizeof(clientaddr);
NSLog(@" Be prepared to accept ");
//accept function
// The second parameter is used to return the protocol address of the client .
// The third parameter is the length of the protocol address
clientfd = accept(fd, (struct sockaddr )&clientaddr, &addrLen);
success = (clientfd!= -1);
if (success) {
char buf[1024];
ssize_t count;// Used to receive the return value of the function
ssize_t len = sizeof(buf);
do{
//recv() The number of bytes of data actually read into the buffer is returned successfully , Erroneous return -1.
count = recv(clientfd,buf,len,0);
if(count < 0){
NSLog(@" bye ");
break;
}
// Output
NSString *str = [NSString stringWithCString:buf encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}while(strcmp(buf, "exit")!=0);
}
// clientaddr.sin_family = AF_INET;
// clientaddr.sin_port = htons(1024);
// clientaddr.sin_addr.s_addr =inet_addr("127.0.0.1");
// Close client : Just close the socket specific TCP Connect
close(clientfd);
}
}
return 0;
// client
import <Foundation/Foundation.h>
include<sys/socket.h>// Provide socket Functions and data structures
include<netinet/in.h>// Define the data structure
include <arpa/inet.h>// Provide IP Address translation function
int main() {
// Client order :Socket->bind->connect->send->close
// Create a socket
// Socket : Source ip Address and purpose ip Address as well as Combination of source port number and destination port number . Used to identify the server requested by the client .
//domain: Domain of definition , Currently only supported AF_INET(Internet The address format of )
//type: Socket type description .SOCK_STREAM streaming (TCP),SOCK_DGRAM Datagram (UDP)
//protocol: The protocol used by the socket , If you do not want to specify , You can use 0 Express
int fd = socket(AF_INET, SOCK_STREAM, 0);
printf("%d\n",fd);
// As long as it doesn't equal -1, Indicates that the creation was successful .
BOOL success= (fd != -1);
//sockaddr_in Is the address form of socket in the network environment
struct sockaddr_in addr;
// Create a shaping variable , Used to reflect errors in network connection
int err;
if(success){
printf("socket success \n");
// Memory initialization
//sizeof: Calculate the number of bytes in the data space
memset(&addr,0,sizeof(addr));
// Yes addr Structure
addr.sin_family = AF_INET;//AF_INET adopt Ipv4 communicate
// Set the network address
addr.sin_addr.s_addr =INADDR_ANY;//INADDR_ANY The specified address is 0.0.0.0 The address of . Indicates an indefinite address , Or imagine a “ Any address ”.
// take socket Bind to a specific host address and port number , Successful binding will return , Failure can also
err = bind(fd, (const struct sockaddr *)&addr, sizeof(addr));
success = (err == 0);//if(err == 0){success = true;}
}
if (success) {
printf("bind success \n");
// Create the server address to connect to
struct sockaddr_in serveraddr;
// Memory initialization
memset(&serveraddr, 0, sizeof(serveraddr));
// Set structure (host to net short)
serveraddr.sin_port = htons(1024);// Converts the unsigned short integer of the host to network byte order
serveraddr.sin_len = sizeof(serveraddr);
serveraddr.sin_family = AF_INET;
// Set the server address
serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");// This address is local , Generally used to test the use of .
printf(" Connecting ...\n");
// The client sends a connection request to the server , Connection successful return 0, Failure to return -1
err = connect(fd, (const struct sockaddr *)&serveraddr, sizeof(serveraddr));
success =(err == 0);
socklen_t addrLen = sizeof(serveraddr);;// Client address length
if(success){
printf(" Successful connection ...\n");
//getsockname You can correctly obtain the information that you are currently communicating with socketIP Port and other information
getsockname(fd, (struct sockaddr *)&addr, &addrLen);
success = (err == 0);
//inet_ntoa: Will a IP String converted to Internet standard dot format
//ntohs: Convert network byte order to host byte order
printf(" Local address :%s, Port number :%d\n",inet_ntoa(addr.sin_addr),ntohs(addr.sin_port));
// Send a message
char buf[1024];
do{
printf(" Please enter information :");
// puts(buf);
scanf("%s",buf);
send(fd,buf,1024,0);
}while (strcmp(buf, "exit")!=0);// When the input exit Out of the loop , end
}
else {
printf(" The connection fails ...\n");
}
}
return 0;
}
</pre> 边栏推荐
- The new purchased machines with large customized images are slow to enter the system
- Tencent cloud won the first place in the cloud natural language understanding classification task
- IP address and subnet partition are very important. This article is very fragrant!
- Designing complex messaging systems using bridging patterns
- BIM model example
- Question: can you get download the resources of Baidu online disk?
- How to obtain the information of easydss single / multiple live streams through the API interface?
- How to batch output ean 13 code to pictures
- The dealer management and control platform in the leather industry simplifies the purchase approval process and easily controls agents
- Thoroughly explain the details of the simple factory that you haven't paid attention to
猜你喜欢

2020 language and intelligent technology competition was launched, and Baidu provided the largest Chinese data set

How to fill in and register e-mail, and open mass mailing software for free

If there are enumerations in the entity object, the conversion of enumerations can be carried out with @jsonvalue and @enumvalue annotations

Introduction to development model + test model

Advanced BOM tool intelligent packaging function

Leetcode969: pancake sorting (medium, dynamic programming)

163 mailbox login portal display, enterprise mailbox computer version login portal

application. Yaml configuring multiple running environments

BIM model example
Cloudpods golang practice
随机推荐
How to build a website? These things should be paid attention to
How do I fix the iPhone green screen problem? Try these solutions
What is vxlan? What are its advantages?
How to view the speech synthesis platform how to use the speech synthesis platform
The same set of code returns normally sometimes and reports an error sometimes. Signature error authfailure SignatureFailure
What is the domain name trademark? What are the registration conditions for domain names and trademarks?
Which cloud game service provider is more reliable when the cloud game server is open source
Start tcapulusdb process
Mainstay of network detection - nping User Guide
Tencent cloud temporary secret key scheme - character recognition example
IP address and subnet partition are very important. This article is very fragrant!
2020 language and intelligent technology competition was launched, and Baidu provided the largest Chinese data set
Code 128 barcode details
What is the cloud desktop server configuration? What are the application scenarios of cloud desktop?
How long can the trademark registration be completed? How to improve the speed of trademark registration?
Is the trademark registered domain name legal? How do trademarks register domain names?
Layout use case
A complete collection of SQL commands. Each command has an example. Xiaobai can become a God after reading it!
Leetcode969: pancake sorting (medium, dynamic programming)
How to design and make ppt gradient effect?