sorket编程中的端口重用

[复制链接]
查看450 | 回复5 | 6 天前 | 显示全部楼层 |阅读模式
本帖最后由 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绑定。

回复

使用道具 举报

回帖奖励 +2 金钱

厉害了
回复

使用道具 举报

WT_0213 | 6 天前 | 显示全部楼层

回帖奖励 +2 金钱

学到了
回复

使用道具 举报

回帖奖励 +2 金钱

学到了
选择去发光,而不是被照亮
回复

使用道具 举报

iiv | 6 天前 | 显示全部楼层

回帖奖励 +2 金钱

学一下
回复

使用道具 举报

qhsj | 6 天前 | 显示全部楼层

回帖奖励 +2 金钱

学习了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则