客户端
消息模型
//
// MsgModel.h
// socket(client)
//
// Created by zmx on 16/1/8.
// Copyright © 2016年 zmx. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MsgModel : NSObject
@property (nonatomic,copy) NSString *msg;
@property (nonatomic,assign) BOOL me;
@end
//
// MsgModel.m
// socket(client)
//
// Created by zmx on 16/1/8.
// Copyright © 2016年 zmx. All rights reserved.
//
#import "MsgModel.h"
@implementation MsgModel
@end
消息Cell
//
// MsgCell.h
// socket(client)
//
// Created by zmx on 16/1/8.
// Copyright © 2016年 zmx. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MsgCell :UITableViewCell
@property (weak, nonatomic) IBOutletUILabel *label;
@end
//
// MsgCell.m
// socket(client)
//
// Created by zmx on 16/1/8.
// Copyright © 2016年 zmx. All rights reserved.
//
#import "MsgCell.h"
@implementation MsgCell
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selectedanimated:animated];
// Configure the view for the selected state
}
@end
//
// ViewController.m
// socket(client)
//
// Created by zmx on 16/1/7.
// Copyright © 2016年 zmx. All rights reserved.
//
#import "ViewController.h"
#import "MsgModel.h"
#import "MsgCell.h"
#import "GCDAsyncSocket.h"
@interface ViewController () <GCDAsyncSocketDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutletUITableView *tableView;
@property (weak, nonatomic) IBOutletUIView *ReplyView;
@property (weak, nonatomic) IBOutletUITextField *textField;
@property (weak, nonatomic) IBOutletNSLayoutConstraint *bottomConstraint;
@property (nonatomic,strong) GCDAsyncSocket *socket;
@property (nonatomic,strong) GCDAsyncSocket *server;
@property (nonatomic,strong) NSMutableArray *msgs;
@end
@implementation ViewController
- (NSMutableArray *)msgs {
if (_msgs ==nil) {
_msgs = [NSMutableArrayarray];
}
return _msgs;
}
- (IBAction)send:(id)sender {
[self.viewendEditing:YES];
NSString *str = self.textField.text;
[self.serverwriteData:[strdataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1tag:0];
self.textField.text =@"";
MsgModel *msgModel = [[MsgModelalloc] init];
msgModel.msg = str;
msgModel.me = YES;
[self.msgsaddObject:msgModel];
[self.tableViewreloadData];
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.socket = [[GCDAsyncSocketalloc] initWithDelegate:selfdelegateQueue:dispatch_get_global_queue(0,0) socketQueue:dispatch_get_main_queue()];
[self.socketconnectToHost:@"192.168.1.107"onPort:2345error:nil];
NSTimer *timer = [NSTimerscheduledTimerWithTimeInterval:1 /60.0 target:selfselector:@selector(updateTimer)userInfo:nilrepeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
self.tableView.estimatedRowHeight =100;
self.tableView.rowHeight =UITableViewAutomaticDimension;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(changeFrame:)name:UIKeyboardWillChangeFrameNotificationobject:nil];
}
- (void)dealloc {
[[NSNotificationCenterdefaultCenter] removeObserver:self];
}
- (void)changeFrame:(NSNotification *)notification {
CGFloat y = ((NSValue *)notification.userInfo[UIKeyboardFrameEndUserInfoKey]).CGRectValue.origin.y;
self.bottomConstraint.constant = [UIScreenmainScreen].bounds.size.height - y;
[UIViewanimateWithDuration:0.25animations:^{
[self.viewlayoutIfNeeded];
}];
}
- (void)updateTimer {
[self.serverreadDataWithTimeout:-1tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
self.server = sock;
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *str = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
MsgModel *msgModel = [[MsgModelalloc] init];
msgModel.msg = str;
msgModel.me = NO;
[self.msgsaddObject:msgModel];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableViewreloadData];
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.msgs.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MsgModel *msgModel = self.msgs[indexPath.row];
NSString *identifier = @"";
if (msgModel.me) {
identifier = @"Right";
} else {
identifier = @"Left";
}
MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[NSBundlemainBundle] loadNibNamed:identifierowner:niloptions:nil]firstObject];
}
cell.label.text = msgModel.msg;
return cell;
}
@end
服务器端
//
// ViewController.m
// socket
//
// Created by zmx on 16/1/7.
// Copyright © 2016年 zmx. All rights reserved.
//
#import "ViewController.h"
#import "GCDAsyncSocket.h"
@interface ViewController () <GCDAsyncSocketDelegate>
@property (nonatomic,strong) GCDAsyncSocket *socket;
@property (nonatomic,strong) NSMutableArray *clients;
@end
@implementation ViewController
- (NSMutableArray *)clients {
if (_clients ==nil) {
_clients = [NSMutableArrayarray];
}
return_clients;
}
- (void)viewDidLoad {
[superviewDidLoad];
self.socket = [[GCDAsyncSocketalloc] initWithDelegate:selfdelegateQueue:dispatch_get_global_queue(0,0) socketQueue:dispatch_get_main_queue()];
[self.socketacceptOnInterface:@"192.168.1.107"port:2345error:nil];
NSTimer *timer = [NSTimerscheduledTimerWithTimeInterval:1 /60.0 target:selfselector:@selector(updateTimer)userInfo:nilrepeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)updateTimer {
for (GCDAsyncSocket *socketin self.clients) {
[socket readDataWithTimeout:-1tag:0];
}
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
[newSocket writeData:[@"asdsd"dataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1tag:0];
[self.clientsaddObject:newSocket];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
for (GCDAsyncSocket *socketin self.clients) {
if (socket != sock) {
[socket writeData:data withTimeout:-1 tag:0];
}
}
}
@end
运行结果
命令行显示
bogon:~ zmx$ telnet 192.168.1.107 2345
Trying 192.168.1.107...
Connected to bogon.
Escape character is '^]'.
asdsd dkasf
adsjkv
ALKGN kladsvn
vjdbska djskv