//
// ViewController.m
// socket
//
// Created by admin on 2018/1/18.
// Copyright © 2018年 admin. All rights reserved.
//
#import "ViewController.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *ipTextField;
@property (weak, nonatomic) IBOutlet UITextField *portField;
@property (weak, nonatomic) IBOutlet UIButton *connectBtn;
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (weak, nonatomic) IBOutlet UITextField *sendMsgField;
@property (weak, nonatomic) IBOutlet UILabel *recvLabel;
@property (nonatomic, assign) int clientSocket;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//点击连接按钮
- (IBAction)connectBtnAction:(id)sender {
[self connect:self.ipTextField.text port:[self.portField.text intValue]];
}
//点击发送按钮
- (IBAction)sendBtnAction:(id)sender {
self.recvLabel.text = [self sendAndRecv:self.sendMsgField.text];
NSLog(@"完毕");
}
//点击关闭按钮
- (IBAction)closeBtnAction:(id)sender {
close(self.clientSocket);
NSLog(@"连接关闭");
}
//1.连接服务器
- (BOOL)connect:(NSString *)ip port:(int)port{
//创建socket
int clientSocket= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
self.clientSocket = clientSocket;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip.UTF8String);
addr.sin_port = htons(port);
int result = connect(clientSocket, (const struct sockaddr *) &addr, sizeof(addr));
if (result == 0) {
return YES;
}else{
return NO;
}
}
//1.发送和接受数据
- (NSString *)sendAndRecv:(NSString *)sendMsg{
//向服务器发送数据
const char *msg = sendMsg.UTF8String;
//成功发送返回发送的字节数, 失败返回-1
ssize_t sendCount = send(self.clientSocket, msg, strlen(msg), 0);
NSLog(@"发送的字节数%zd", sendCount);
//接受服务器返回的数据
//返回的是实际接受的字节个数
uint8_t buffer[1024];
ssize_t recvCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);
NSLog(@"接收的字节数%zd", recvCount);
NSData *data = [NSData dataWithBytes:buffer length:recvCount];
NSString *recvMsg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return recvMsg;
}
@end
image.png
网友评论