一个基于UDP的简单的聊天Demo(用C语言、python、GCDAsyncUdpSocket来实现UDP通信)

推荐阅读:备战2020——iOS全新面试题总结

一、分别用C语言、python、GCDAsyncUdpSocket来实现UDP通信

1、C语言方式
  • 首先初始化socket对象,Udp要用SOCK_DGRAM
  • 然后初始化sockaddr_in网络通信对象,如果作为服务端要绑定socket对象与通信链接,来接收消息
  • 然后开启一个循环,循环调用recvfrom来接收消息
  • 收到消息后,保存下发消息对象的地址,以便之后回复消息
- (void)initCSocket
{

    char receiveBuffer[1024];

    __uint32_t nSize = sizeof(struct sockaddr);

    if ((_listenfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {

        perror("socket() error. Failed to initiate a socket");
    }

    bzero(&_addr, sizeof(_addr));

    _addr.sin_family = AF_INET;

    _addr.sin_port = htons(_destPort);

    if(bind(_listenfd, (struct sockaddr *)&_addr, sizeof(_addr)) == -1)
    {
        perror("Bind() error.");
    }

    _addr.sin_addr.s_addr = inet_addr([_destHost UTF8String]);//ip可是是本服务器的ip,也可以用宏INADDR_ANY代替,代表0.0.0.0,表明所有地址

    while(true){

        long strLen = recvfrom(_listenfd, receiveBuffer, sizeof(receiveBuffer), 0, (struct sockaddr *)&_addr, &nSize);

        NSString * message = [[NSString alloc] initWithBytes:receiveBuffer length:strLen encoding:NSUTF8StringEncoding];

        _destPort = ntohs(_addr.sin_port);

        _destHost = [[NSString alloc] initWithUTF8String:inet_ntoa(_addr.sin_addr)];

        NSLog(@"来自%@---%zd:%@",_destHost,_destPort,message);
    }
}

  • 由于开启while循环来一直接收消息,所以为了避免阻塞主线程,这里要将initCSocket函数放在子线程中调用
dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [self initCSocket];
    });

  • 调用sendto方法来发送消息
- (void)sendMessage:(NSString *)message
{
    NSData *sendData = [message dataUsingEncoding:NSUTF8StringEncoding];

    sendto(_listenfd, [sendData bytes], [sendData length], 0, (struct sockaddr *)&_addr, sizeof(struct sockaddr));
}

2、GCDAsyncUdpSocket方式
  • GCDAsyncUdpSocket地址
  • 首先初始化Socket对象

  • 绑定端口,调用beginReceiving:方法来接收消息

- (void)initGCDSocket
{
    _receiveSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
                                                   delegateQueue:dispatch_get_global_queue(0, 0)];
    NSError *error;

    // 绑定一个端口(可选),如果不绑定端口, 那么就会随机产生一个随机的唯一的端口
    // 端口数字范围(1024,2^16-1)
    [_receiveSocket bindToPort:test_port error:&error];

    if (error) {
        NSLog(@"服务器绑定失败");
    }
    // 开始接收对方发来的消息
    [_receiveSocket beginReceiving:nil];
}

  • 在代理方法里获取到对方发过来的消息,记录下主机和端口,以便之后回复消息
#pragma mark - GCDAsyncUdpSocketDelegate
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext {

    NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    _destPort = [GCDAsyncUdpSocket portFromAddress:address];

    _destHost = [GCDAsyncUdpSocket hostFromAddress:address];

    NSLog(@"来自%@---%zd:%@",_destHost,_destPort,message);
}

  • 调用sendData:(NSData *)data toHost:(NSString *)host port:(uint16_t)port withTimeout:(NSTimeInterval)timeout tag:(long)tag方法来发送消息
- (void)sendMessage:(NSString *)message
{
    NSData *sendData = [message dataUsingEncoding:NSUTF8StringEncoding];

    [_receiveSocket sendData:sendData toHost:_destHost port:_destPort withTimeout:60 tag:500];
}

3、python方式

python方式就比较简单了

  • 初始化socket,绑定端口
socket = socket(AF_INET, SOCK_DGRAM)

socket.bind(('', port))

  • 循环接收消息
while True:
    message, address = socket.recvfrom(2048)
    print address,message

  • 发送消息
socket.sendto(message, address)

二、利用python实现Udp通信demo

  • 创建两个python文件,分别作为客户端和服务端,然后同时运行

  • 客户端

from socket import *
host = '127.0.0.1'
port = 12000
socket = socket(AF_INET, SOCK_DGRAM)
while True:
    message = raw_input('input message ,print 0 to close :\n')
    socket.sendto(message, (host, port))
    if message == '0':
        socket.close()
        break
    receiveMessage, serverAddress = socket.recvfrom(2048)
    print receiveMessage,serverAddress

  • 服务端
from socket import *
port = 12000
socket = socket(AF_INET, SOCK_DGRAM)
socket.bind(('', port))
print 'server is ready to receive'
count = 0
while True:
    message, address = socket.recvfrom(2048)
    print address,message
    count = count + 1
    if message == '0':
        socket.close()
        break
    else:
        message = raw_input('input message ,print 0 to close :\n')
        socket.sendto(message, address)

  • 客户端打印
/usr/local/bin/python2.7 /Users/wangyong/Desktop/other/python/UDPClient.py
input message ,print 0 to close :
hello,服务端
hello,客户端 ('10.208.61.53', 12000)
input message ,print 0 to close :
结束通信吧我们
好的 ('10.208.61.53', 12000)
input message ,print 0 to close :
0

Process finished with exit code 0

  • 服务端打印
/usr/local/bin/python2.7 /Users/wangyong/Desktop/other/python/UDPServer.py
server is ready to receive
('10.208.61.53', 53500) hello,服务端
input message ,print 0 to close :
hello,客户端
('10.208.61.53', 53500) 结束通信吧我们
input message ,print 0 to close :
好的
('10.208.61.53', 53500) 0

Process finished with exit code 0

三、iOS端基于UDP的简易聊天demo

1、UdpManager

Udp通信用C语言版和GCDAsyncUdpSocket都可以,封装在UdpManager

  • initSocketWithReceiveHandle:(dispatch_block_t)receiveHandle:初始化socket相关,receiveHandle是接收到消息后的回调
  • sendMessage:(NSString *)message:发送消息
  • messageArray:消息列表,包括接收到的和发送出去的消息
+ (void)initSocketWithReceiveHandle:(dispatch_block_t)receiveHandle;

+ (void)sendMessage:(NSString *)message;

+ (NSMutableArray *)messageArray;

消息内容用MessageModel,其中role代表消息发送对象,为0即是接收到的消息,1为自己发送的消息

@interface MessageModel:NSObject

@property (nonatomic, copy) NSString *message;

@property(nonatomic,assign) NSInteger role;

@end

2、ViewController

控制器里调用UdpManager初始化socket

[UdpManager initSocketWithReceiveHandle:^{

        dispatch_async(dispatch_get_main_queue(), ^{

            self.title = [NSString stringWithFormat:@"%@---%@",[[UdpManager shareManager] valueForKey:@"_destHost"],[[UdpManager shareManager] valueForKey:@"_destPort"]];

            [self reloadData];
        });
    }];

在代理方法textFieldShouldReturn即点击键盘的发送按钮时发送编辑好的消息

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (self.textField.text.length == 0) return YES;

    [UdpManager sendMessage:self.textField.text];

    [self reloadData];

    self.textField.text = nil;

    return YES;
}

发送或者接收到新消息后都会将消息添加到messageArray里,并刷新页面

- (void)sendMessage:(NSString *)message
{
    NSData *sendData = [message dataUsingEncoding:NSUTF8StringEncoding];

    [self.messageArray addObject:[[MessageModel alloc] initWithMessage:message role:1]];

#ifdef UseGCDUdpSocket

    // 该函数只是启动一次发送 它本身不进行数据的发送, 而是让后台的线程慢慢的发送 也就是说这个函数调用完成后,数据并没有立刻发送,异步发送
    [_receiveSocket sendData:sendData toHost:_destHost port:_destPort withTimeout:60 tag:500];

#else

    sendto(_listenfd, [sendData bytes], [sendData length], 0, (struct sockaddr *)&_addr, sizeof(struct sockaddr));

#endif
}

UI就不多做介绍了,控制器里只有一个显示接收和发送消息内容列表的tableView及一个编辑消息的输入框textField。大概就这些内容,只是个简易的demo,只实现了接收发送文字消息的功能,并没有做更多优化

3、测试

分别用模拟器和真机运行,或者可以配合刚才的python程序测试.
test_host就直接用电脑ip即可

image
  • 然后手机先发送消息到模拟器上,模拟器就可以根据记录下的手机的主机和端口回复消息了。这里手机连外网也是可以的

  • 效果图如下

    image

Github代码地址

你可能感兴趣的:(一个基于UDP的简单的聊天Demo(用C语言、python、GCDAsyncUdpSocket来实现UDP通信))