发帖
5 0 0

sorket编程中的端口重用

qq243559086
高级会员

14

主题

0

回帖

634

积分

高级会员

积分
634
爱星物联IoT云平台 1000 5 2024-9-13 13:43:40
本帖最后由 qq243559086 于 2024-9-13 13:42 编辑

Android中:
  1. try {
  2.     ServerSocket serverSocket = new ServerSocket(null);// 这里设置为null,setReuseAddress才会有效
  3.     serverSocket.setReuseAddress(true); // 先设置端口复用
  4.     serverSocket.bind(new InetSocketAddress(12345));
  5. } catch (IOException e) {
  6.     throw new RuntimeException(e);
  7. }

  8. try {
  9.     DatagramSocket ds = new DatagramSocket(null);// 这里设置为null,setReuseAddress才会有效
  10.     ds.setReuseAddress(true);// 可复用端口号
  11.     ds.bind(new InetSocketAddress(12345));
  12. } catch (SocketException e) {
  13.     throw new RuntimeException(e);
  14. }
复制代码
iOS中:
  1. GCDAsyncUdpSocket *_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
  2. NSError *error;
  3. [_udpSocket enableReusePort:YES error:&error];
  4. // [_udpSocket bindToPort:12345 error:&error];// 不设置enableReusePort:YES, 就必须先绑定端口才能 receive
  5. if (error) {
  6.     NSLog(@"端口绑定--%@--", error);
  7.     return nil;
  8. }
  9. error = nil;
  10. [_udpSocket beginReceiving:&error];
  11. if (error) {
  12.     NSLog(@"--%@--", error);
  13.     return nil;
  14. }
复制代码
设置端口复用的意义在于,当占用此端口的sorket关闭后,可以立即用其他sorket绑定此端口,否则就要等待系统设定的超时时间后才能绑定此端口。
端口复用不要理解成,一个端口可以同时被多个sorket绑定。

──── 0人觉得很赞 ────

使用道具 举报

回帖奖励 +2 金钱

厉害了
2024-9-13 15:08:45

回帖奖励 +2 金钱

学到了
2024-9-13 16:12:05

回帖奖励 +2 金钱

学到了
2024-9-13 20:23:50

回帖奖励 +2 金钱

学一下
2024-9-13 20:50:42

回帖奖励 +2 金钱

学习了
您需要登录后才可以回帖 立即登录
高级模式
返回
统计信息
  • 会员数: 28220 个
  • 话题数: 40145 篇