Python socket/socketserver 源码
Socket源码
Cpython版本:v3.7.5
socket.py

1 # Wrapper module for _socket, providing some additional facilities 2 # implemented in Python. 3 4 """\ 5 This module provides socket operations and some related functions. 6 On Unix, it supports IP (Internet Protocol) and Unix domain sockets. 7 On other systems, it only supports IP. Functions specific for a 8 socket are available as methods of the socket object. 9 10 Functions: 11 12 socket() -- create a new socket object 13 socketpair() -- create a pair of new socket objects [*] 14 fromfd() -- create a socket object from an open file descriptor [*] 15 fromshare() -- create a socket object from data received from socket.share() [*] 16 gethostname() -- return the current hostname 17 gethostbyname() -- map a hostname to its IP number 18 gethostbyaddr() -- map an IP number or hostname to DNS info 19 getservbyname() -- map a service name and a protocol name to a port number 20 getprotobyname() -- map a protocol name (e.g. 'tcp') to a number 21 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order 22 htons(), htonl() -- convert 16, 32 bit int from host to network byte order 23 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format 24 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) 25 socket.getdefaulttimeout() -- get the default timeout value 26 socket.setdefaulttimeout() -- set the default timeout value 27 create_connection() -- connects to an address, with an optional timeout and 28 optional source address. 29 30 [*] not available on all platforms! 31 32 Special objects: 33 34 SocketType -- type object for socket objects 35 error -- exception raised for I/O errors 36 has_ipv6 -- boolean value indicating if IPv6 is supported 37 38 IntEnum constants: 39 40 AF_INET, AF_UNIX -- socket domains (first argument to socket() call) 41 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) 42 43 Integer constants: 44 45 Many other constants may be defined; these may be used in calls to 46 the setsockopt() and getsockopt() methods. 47 """ 48 49 import _socket 50 from _socket import * 51 52 import os, sys, io, selectors 53 from enum import IntEnum, IntFlag 54 55 try: 56 import errno 57 except ImportError: 58 errno = None 59 EBADF = getattr(errno, 'EBADF', 9) 60 EAGAIN = getattr(errno, 'EAGAIN', 11) 61 EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11) 62 63 __all__ = ["fromfd", "getfqdn", "create_connection", 64 "AddressFamily", "SocketKind"] 65 __all__.extend(os._get_exports_list(_socket)) 66 67 # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for 68 # nicer string representations. 69 # Note that _socket only knows about the integer values. The public interface 70 # in this module understands the enums and translates them back from integers 71 # where needed (e.g. .family property of a socket object). 72 73 IntEnum._convert( 74 'AddressFamily', 75 __name__, 76 lambda C: C.isupper() and C.startswith('AF_')) 77 78 IntEnum._convert( 79 'SocketKind', 80 __name__, 81 lambda C: C.isupper() and C.startswith('SOCK_')) 82 83 IntFlag._convert( 84 'MsgFlag', 85 __name__, 86 lambda C: C.isupper() and C.startswith('MSG_')) 87 88 IntFlag._convert( 89 'AddressInfo', 90 __name__, 91 lambda C: C.isupper() and C.startswith('AI_')) 92 93 _LOCALHOST = '127.0.0.1' 94 _LOCALHOST_V6 = '::1' 95 96 97 def _intenum_converter(value, enum_klass): 98 """Convert a numeric family value to an IntEnum member. 99 100 If it's not a known member, return the numeric value itself. 101 """ 102 try: 103 return enum_klass(value) 104 except ValueError: 105 return value 106 107 _realsocket = socket 108 109 # WSA error codes 110 if sys.platform.lower().startswith("win"): 111 errorTab = {} 112 errorTab[10004] = "The operation was interrupted." 113 errorTab[10009] = "A bad file handle was passed." 114 errorTab[10013] = "Permission denied." 115 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT 116 errorTab[10022] = "An invalid operation was attempted." 117 errorTab[10035] = "The socket operation would block" 118 errorTab[10036] = "A blocking operation is already in progress." 119 errorTab[10048] = "The network address is in use." 120 errorTab[10054] = "The connection has been reset." 121 errorTab[10058] = "The network has been shut down." 122 errorTab[10060] = "The operation timed out." 123 errorTab[10061] = "Connection refused." 124 errorTab[10063] = "The name is too long." 125 errorTab[10064] = "The host is down." 126 errorTab[10065] = "The host is unreachable." 127 __all__.append("errorTab") 128 129 130 class _GiveupOnSendfile(Exception): pass 131 132 133 class socket(_socket.socket): 134 135 """A subclass of _socket.socket adding the makefile() method.""" 136 137 __slots__ = ["__weakref__", "_io_refs", "_closed"] 138 139 def __init__(self, family=-1, type=-1, proto=-1, fileno=None): 140 # For user code address family and type values are IntEnum members, but 141 # for the underlying _socket.socket they're just integers. The 142 # constructor of _socket.socket converts the given argument to an 143 # integer automatically. 144 if fileno is None: 145 if family == -1: 146 family = AF_INET 147 if type == -1: 148 type = SOCK_STREAM 149 if proto == -1: 150 proto = 0 151 _socket.socket.__init__(self, family, type, proto, fileno) 152 self._io_refs = 0 153 self._closed = False 154 155 def __enter__(self): 156 return self 157 158 def __exit__(self, *args): 159 if not self._closed: 160 self.close() 161 162 def __repr__(self): 163 """Wrap __repr__() to reveal the real class name and socket 164 address(es). 165 """ 166 closed = getattr(self, '_closed', False) 167 s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \ 168 % (self.__class__.__module__, 169 self.__class__.__qualname__, 170 " [closed]" if closed else "", 171 self.fileno(), 172 self.family, 173 self.type, 174 self.proto) 175 if not closed: 176 try: 177 laddr = self.getsockname() 178 if laddr: 179 s += ", laddr=%s" % str(laddr) 180 except error: 181 pass 182 try: 183 raddr = self.getpeername() 184 if raddr: 185 s += ", raddr=%s" % str(raddr) 186 except error: 187 pass 188 s += '>' 189 return s 190 191 def __getstate__(self): 192 raise TypeError("Cannot serialize socket object") 193 194 def dup(self): 195 """dup() -> socket object 196 197 Duplicate the socket. Return a new socket object connected to the same 198 system resource. The new socket is non-inheritable. 199 """ 200 fd = dup(self.fileno()) 201 sock = self.__class__(self.family, self.type, self.proto, fileno=fd) 202 sock.settimeout(self.gettimeout()) 203 return sock 204 205 def accept(self): 206 """accept() -> (socket object, address info) 207 208 Wait for an incoming connection. Return a new socket 209 representing the connection, and the address of the client. 210 For IP sockets, the address info is a pair (hostaddr, port). 211 """ 212 fd, addr = self._accept() 213 sock = socket(self.family, self.type, self.proto, fileno=fd) 214 # Issue #7995: if no default timeout is set and the listening 215 # socket had a (non-zero) timeout, force the new socket in blocking 216 # mode to override platform-specific socket flags inheritance. 217 if getdefaulttimeout() is None and self.gettimeout(): 218 sock.setblocking(True) 219 return sock, addr 220 221 def makefile(self, mode="r", buffering=None, *, 222 encoding=None, errors=None, newline=None): 223 """makefile(...) -> an I/O stream connected to the socket 224 225 The arguments are as for io.open() after the filename, except the only 226 supported mode values are 'r' (default), 'w' and 'b'. 227 """ 228 # XXX refactor to share code? 229 if not set(mode) <= {"r", "w", "b"}: 230 raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) 231 writing = "w" in mode 232 reading = "r" in mode or not writing 233 assert reading or writing 234 binary = "b" in mode 235 rawmode = "" 236 if reading: 237 rawmode += "r" 238 if writing: 239 rawmode += "w" 240 raw = SocketIO(self, rawmode) 241 self._io_refs += 1 242 if buffering is None: 243 buffering = -1 244 if buffering < 0: 245 buffering = io.DEFAULT_BUFFER_SIZE 246 if buffering == 0: 247 if not binary: 248 raise ValueError("unbuffered streams must be binary") 249 return raw 250 if reading and writing: 251 buffer = io.BufferedRWPair(raw, raw, buffering) 252 elif reading: 253 buffer = io.BufferedReader(raw, buffering) 254 else: 255 assert writing 256 buffer = io.BufferedWriter(raw, buffering) 257 if binary: 258 return buffer 259 text = io.TextIOWrapper(buffer, encoding, errors, newline) 260 text.mode = mode 261 return text 262 263 if hasattr(os, 'sendfile'): 264 265 def _sendfile_use_sendfile(self, file, offset=0, count=None): 266 self._check_sendfile_params(file, offset, count) 267 sockno = self.fileno() 268 try: 269 fileno = file.fileno() 270 except (AttributeError, io.UnsupportedOperation) as err: 271 raise _GiveupOnSendfile(err) # not a regular file 272 try: 273 fsize = os.fstat(fileno).st_size 274 except OSError as err: 275 raise _GiveupOnSendfile(err) # not a regular file 276 if not fsize: 277 return 0 # empty file 278 blocksize = fsize if not count else count 279 280 timeout = self.gettimeout() 281 if timeout == 0: 282 raise ValueError("non-blocking sockets are not supported") 283 # poll/select have the advantage of not requiring any 284 # extra file descriptor, contrarily to epoll/kqueue 285 # (also, they require a single syscall). 286 if hasattr(selectors, 'PollSelector'): 287 selector = selectors.PollSelector() 288 else: 289 selector = selectors.SelectSelector() 290 selector.register(sockno, selectors.EVENT_WRITE) 291 292 total_sent = 0 293 # localize variable access to minimize overhead 294 selector_select = selector.select 295 os_sendfile = os.sendfile 296 try: 297 while True: 298 if timeout and not selector_select(timeout): 299 raise _socket.timeout('timed out') 300 if count: 301 blocksize = count - total_sent 302 if blocksize <= 0: 303 break 304 try: 305 sent = os_sendfile(sockno, fileno, offset, blocksize) 306 except BlockingIOError: 307 if not timeout: 308 # Block until the socket is ready to send some 309 # data; avoids hogging CPU resources. 310 selector_select() 311 continue 312 except OSError as err: 313 if total_sent == 0: 314 # We can get here for different reasons, the main 315 # one being 'file' is not a regular mmap(2)-like 316 # file, in which case we'll fall back on using 317 # plain send(). 318 raise _GiveupOnSendfile(err) 319 raise err from None 320 else: 321 if sent == 0: 322 break # EOF 323 offset += sent 324 total_sent += sent 325 return total_sent 326 finally: 327 if total_sent > 0 and hasattr(file, 'seek'): 328 file.seek(offset) 329 else: 330 def _sendfile_use_sendfile(self, file, offset=0, count=None): 331 raise _GiveupOnSendfile( 332 "os.sendfile() not available on this platform") 333 334 def _sendfile_use_send(self, file, offset=0, count=None): 335 self._check_sendfile_params(file, offset, count) 336 if self.gettimeout() == 0: 337 raise ValueError("non-blocking sockets are not supported") 338 if offset: 339 file.seek(offset) 340 blocksize = min(count, 8192) if count else 8192 341 total_sent = 0 342 # localize variable access to minimize overhead 343 file_read = file.read 344 sock_send = self.send 345 try: 346 while True: 347 if count: 348 blocksize = min(count - total_sent, blocksize) 349 if blocksize <= 0: 350 break 351 data = memoryview(file_read(blocksize)) 352 if not data: 353 break # EOF 354 while True: 355 try: 356 sent = sock_send(data) 357 except BlockingIOError: 358 continue 359 else: 360 total_sent += sent 361 if sent < len(data): 362 data = data[sent:] 363 else: 364 break 365 return total_sent 366 finally: 367 if total_sent > 0 and hasattr(file, 'seek'): 368 file.seek(offset + total_sent) 369 370 def _check_sendfile_params(self, file, offset, count): 371 if 'b' not in getattr(file, 'mode', 'b'): 372 raise ValueError("file should be opened in binary mode") 373 if not self.type & SOCK_STREAM: 374 raise ValueError("only SOCK_STREAM type sockets are supported") 375 if count is not None: 376 if not isinstance(count, int): 377 raise TypeError( 378 "count must be a positive integer (got {!r})".format(count)) 379 if count <= 0: 380 raise ValueError( 381 "count must be a positive integer (got {!r})".format(count)) 382 383 def sendfile(self, file, offset=0, count=None): 384 """sendfile(file[, offset[, count]]) -> sent 385 386 Send a file until EOF is reached by using high-performance 387 os.sendfile() and return the total number of bytes which 388 were sent. 389 *file* must be a regular file object opened in binary mode. 390 If os.sendfile() is not available (e.g. Windows) or file is 391 not a regular file socket.send() will be used instead. 392 *offset* tells from where to start reading the file. 393 If specified, *count* is the total number of bytes to transmit 394 as opposed to sending the file until EOF is reached. 395 File position is updated on return or also in case of error in 396 which case file.tell() can be used to figure out the number of 397 bytes which were sent. 398 The socket must be of SOCK_STREAM type. 399 Non-blocking sockets are not supported. 400 """ 401 try: 402 return self._sendfile_use_sendfile(file, offset, count) 403 except _GiveupOnSendfile: 404 return self._sendfile_use_send(file, offset, count) 405 406 def _decref_socketios(self): 407 if self._io_refs > 0: 408 self._io_refs -= 1 409 if self._closed: 410 self.close() 411 412 def _real_close(self, _ss=_socket.socket): 413 # This function should not reference any globals. See issue #808164. 414 _ss.close(self) 415 416 def close(self): 417 # This function should not reference any globals. See issue #808164. 418 self._closed = True 419 if self._io_refs <= 0: 420 self._real_close() 421 422 def detach(self): 423 """detach() -> file descriptor 424 425 Close the socket object without closing the underlying file descriptor. 426 The object cannot be used after this call, but the file descriptor 427 can be reused for other purposes. The file descriptor is returned. 428 """ 429 self._closed = True 430 return super().detach() 431 432 @property 433 def family(self): 434 """Read-only access to the address family for this socket. 435 """ 436 return _intenum_converter(super().family, AddressFamily) 437 438 @property 439 def type(self): 440 """Read-only access to the socket type. 441 """ 442 return _intenum_converter(super().type, SocketKind) 443 444 if os.name == 'nt': 445 def get_inheritable(self): 446 return os.get_handle_inheritable(self.fileno()) 447 def set_inheritable(self, inheritable): 448 os.set_handle_inheritable(self.fileno(), inheritable) 449 else: 450 def get_inheritable(self): 451 return os.get_inheritable(self.fileno()) 452 def set_inheritable(self, inheritable): 453 os.set_inheritable(self.fileno(), inheritable) 454 get_inheritable.__doc__ = "Get the inheritable flag of the socket" 455 set_inheritable.__doc__ = "Set the inheritable flag of the socket" 456 457 def fromfd(fd, family, type, proto=0): 458 """ fromfd(fd, family, type[, proto]) -> socket object 459 460 Create a socket object from a duplicate of the given file 461 descriptor. The remaining arguments are the same as for socket(). 462 """ 463 nfd = dup(fd) 464 return socket(family, type, proto, nfd) 465 466 if hasattr(_socket.socket, "share"): 467 def fromshare(info): 468 """ fromshare(info) -> socket object 469 470 Create a socket object from the bytes object returned by 471 socket.share(pid). 472 """ 473 return socket(0, 0, 0, info) 474 __all__.append("fromshare") 475 476 if hasattr(_socket, "socketpair"): 477 478 def socketpair(family=None, type=SOCK_STREAM, proto=0): 479 """socketpair([family[, type[, proto]]]) -> (socket object, socket object) 480 481 Create a pair of socket objects from the sockets returned by the platform 482 socketpair() function. 483 The arguments are the same as for socket() except the default family is 484 AF_UNIX if defined on the platform; otherwise, the default is AF_INET. 485 """ 486 if family is None: 487 try: 488 family = AF_UNIX 489 except NameError: 490 family = AF_INET 491 a, b = _socket.socketpair(family, type, proto) 492 a = socket(family, type, proto, a.detach()) 493 b = socket(family, type, proto, b.detach()) 494 return a, b 495 496 else: 497 498 # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain. 499 def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0): 500 if family == AF_INET: 501 host = _LOCALHOST 502 elif family == AF_INET6: 503 host = _LOCALHOST_V6 504 else: 505 raise ValueError("Only AF_INET and AF_INET6 socket address families " 506 "are supported") 507 if type != SOCK_STREAM: 508 raise ValueError("Only SOCK_STREAM socket type is supported") 509 if proto != 0: 510 raise ValueError("Only protocol zero is supported") 511 512 # We create a connected TCP socket. Note the trick with 513 # setblocking(False) that prevents us from having to create a thread. 514 lsock = socket(family, type, proto) 515 try: 516 lsock.bind((host, 0)) 517 lsock.listen() 518 # On IPv6, ignore flow_info and scope_id 519 addr, port = lsock.getsockname()[:2] 520 csock = socket(family, type, proto) 521 try: 522 csock.setblocking(False) 523 try: 524 csock.connect((addr, port)) 525 except (BlockingIOError, InterruptedError): 526 pass 527 csock.setblocking(True) 528 ssock, _ = lsock.accept() 529 except: 530 csock.close() 531 raise 532 finally: 533 lsock.close() 534 return (ssock, csock) 535 __all__.append("socketpair") 536 537 socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object) 538 Create a pair of socket objects from the sockets returned by the platform 539 socketpair() function. 540 The arguments are the same as for socket() except the default family is AF_UNIX 541 if defined on the platform; otherwise, the default is AF_INET. 542 """ 543 544 _blocking_errnos = { EAGAIN, EWOULDBLOCK } 545 546 class SocketIO(io.RawIOBase): 547 548 """Raw I/O implementation for stream sockets. 549 550 This class supports the makefile() method on sockets. It provides 551 the raw I/O interface on top of a socket object. 552 """ 553 554 # One might wonder why not let FileIO do the job instead. There are two 555 # main reasons why FileIO is not adapted: 556 # - it wouldn't work under Windows (where you can't used read() and 557 # write() on a socket handle) 558 # - it wouldn't work with socket timeouts (FileIO would ignore the 559 # timeout and consider the socket non-blocking) 560 561 # XXX More docs 562 563 def __init__(self, sock, mode): 564 if mode not in ("r", "w", "rw", "rb", "wb", "rwb"): 565 raise ValueError("invalid mode: %r" % mode) 566 io.RawIOBase.__init__(self) 567 self._sock = sock 568 if "b" not in mode: 569 mode += "b" 570 self._mode = mode 571 self._reading = "r" in mode 572 self._writing = "w" in mode 573 self._timeout_occurred = False 574 575 def readinto(self, b): 576 """Read up to len(b) bytes into the writable buffer *b* and return 577 the number of bytes read. If the socket is non-blocking and no bytes 578 are available, None is returned. 579 580 If *b* is non-empty, a 0 return value indicates that the connection 581 was shutdown at the other end. 582 """ 583 self._checkClosed() 584 self._checkReadable() 585 if self._timeout_occurred: 586 raise OSError("cannot read from timed out object") 587 while True: 588 try: 589 return self._sock.recv_into(b) 590 except timeout: 591 self._timeout_occurred = True 592 raise 593 except error as e: 594 if e.args[0] in _blocking_errnos: 595 return None 596 raise 597 598 def write(self, b): 599 """Write the given bytes or bytearray object *b* to the socket 600 and return the number of bytes written. This can be less than 601 len(b) if not all data could be written. If the socket is 602 non-blocking and no bytes could be written None is returned. 603 """ 604 self._checkClosed() 605 self._checkWritable() 606 try: 607 return self._sock.send(b) 608 except error as e: 609 # XXX what about EINTR? 610 if e.args[0] in _blocking_errnos: 611 return None 612 raise 613 614 def readable(self): 615 """True if the SocketIO is open for reading. 616 """ 617 if self.closed: 618 raise ValueError("I/O operation on closed socket.") 619 return self._reading 620 621 def writable(self): 622 """True if the SocketIO is open for writing. 623 """ 624 if self.closed: 625 raise ValueError("I/O operation on closed socket.") 626 return self._writing 627 628 def seekable(self): 629 """True if the SocketIO is open for seeking. 630 """ 631 if self.closed: 632 raise ValueError("I/O operation on closed socket.") 633 return super().seekable() 634 635 def fileno(self): 636 """Return the file descriptor of the underlying socket. 637 """ 638 self._checkClosed() 639 return self._sock.fileno() 640 641 @property 642 def name(self): 643 if not self.closed: 644 return self.fileno() 645 else: 646 return -1 647 648 @property 649 def mode(self): 650 return self._mode 651 652 def close(self): 653 """Close the SocketIO object. This doesn't close the underlying 654 socket, except if all references to it have disappeared. 655 """ 656 if self.closed: 657 return 658 io.RawIOBase.close(self) 659 self._sock._decref_socketios() 660 self._sock = None 661 662 663 def getfqdn(name=''): 664 """Get fully qualified domain name from name. 665 666 An empty argument is interpreted as meaning the local host. 667 668 First the hostname returned by gethostbyaddr() is checked, then 669 possibly existing aliases. In case no FQDN is available, hostname 670 from gethostname() is returned. 671 """ 672 name = name.strip() 673 if not name or name == '0.0.0.0': 674 name = gethostname() 675 try: 676 hostname, aliases, ipaddrs = gethostbyaddr(name) 677 except error: 678 pass 679 else: 680 aliases.insert(0, hostname) 681 for name in aliases: 682 if '.' in name: 683 break 684 else: 685 name = hostname 686 return name 687 688 689 _GLOBAL_DEFAULT_TIMEOUT = object() 690 691 def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, 692 source_address=None): 693 """Connect to *address* and return the socket object. 694 695 Convenience function. Connect to *address* (a 2-tuple ``(host, 696 port)``) and return the socket object. Passing the optional 697 *timeout* parameter will set the timeout on the socket instance 698 before attempting to connect. If no *timeout* is supplied, the 699 global default timeout setting returned by :func:`getdefaulttimeout` 700 is used. If *source_address* is set it must be a tuple of (host, port) 701 for the socket to bind as a source address before making the connection. 702 A host of '' or port 0 tells the OS to use the default. 703 """ 704 705 host, port = address 706 err = None 707 for res in getaddrinfo(host, port, 0, SOCK_STREAM): 708 af, socktype, proto, canonname, sa = res 709 sock = None 710 try: 711 sock = socket(af, socktype, proto) 712 if timeout is not _GLOBAL_DEFAULT_TIMEOUT: 713 sock.settimeout(timeout) 714 if source_address: 715 sock.bind(source_address) 716 sock.connect(sa) 717 # Break explicitly a reference cycle 718 err = None 719 return sock 720 721 except error as _: 722 err = _ 723 if sock is not None: 724 sock.close() 725 726 if err is not None: 727 raise err 728 else: 729 raise error("getaddrinfo returns an empty list") 730 731 def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): 732 """Resolve host and port into list of address info entries. 733 734 Translate the host/port argument into a sequence of 5-tuples that contain 735 all the necessary arguments for creating a socket connected to that service. 736 host is a domain name, a string representation of an IPv4/v6 address or 737 None. port is a string service name such as 'http', a numeric port number or 738 None. By passing None as the value of host and port, you can pass NULL to 739 the underlying C API. 740 741 The family, type and proto arguments can be optionally specified in order to 742 narrow the list of addresses returned. Passing zero as a value for each of 743 these arguments selects the full range of results. 744 """ 745 # We override this function since we want to translate the numeric family 746 # and socket type values to enum constants. 747 addrlist = [] 748 for res in _socket.getaddrinfo(host, port, family, type, proto, flags): 749 af, socktype, proto, canonname, sa = res 750 addrlist.append((_intenum_converter(af, AddressFamily), 751 _intenum_converter(socktype, SocketKind), 752 proto, canonname, sa)) 753 return addrlist
_socket.py

1 # encoding: utf-8 2 # module _socket 3 # from (pre-generated) 4 # by generator 1.147 5 """ 6 Implementation module for socket operations. 7 8 See the socket module for documentation. 9 """ 10 # no imports 11 12 # Variables with simple values 13 14 AF_APPLETALK = 16 15 AF_DECnet = 12 16 AF_INET = 2 17 AF_INET6 = 23 18 AF_IPX = 6 19 AF_IRDA = 26 20 AF_SNA = 11 21 AF_UNSPEC = 0 22 23 AI_ADDRCONFIG = 1024 24 AI_ALL = 256 25 AI_CANONNAME = 2 26 AI_NUMERICHOST = 4 27 AI_NUMERICSERV = 8 28 AI_PASSIVE = 1 29 AI_V4MAPPED = 2048 30 31 EAI_AGAIN = 11002 32 EAI_BADFLAGS = 10022 33 EAI_FAIL = 11003 34 EAI_FAMILY = 10047 35 EAI_MEMORY = 8 36 EAI_NODATA = 11001 37 EAI_NONAME = 11001 38 EAI_SERVICE = 10109 39 EAI_SOCKTYPE = 10044 40 41 has_ipv6 = True 42 43 INADDR_ALLHOSTS_GROUP = -536870911 44 45 INADDR_ANY = 0 46 INADDR_BROADCAST = -1 47 INADDR_LOOPBACK = 2130706433 48 49 INADDR_MAX_LOCAL_GROUP = -536870657 50 51 INADDR_NONE = -1 52 53 INADDR_UNSPEC_GROUP = -536870912 54 55 IPPORT_RESERVED = 1024 56 IPPORT_USERRESERVED = 5000 57 58 IPPROTO_ICMP = 1 59 IPPROTO_IP = 0 60 IPPROTO_RAW = 255 61 IPPROTO_TCP = 6 62 IPPROTO_UDP = 17 63 64 IPV6_CHECKSUM = 26 65 IPV6_DONTFRAG = 14 66 IPV6_HOPLIMIT = 21 67 IPV6_HOPOPTS = 1 68 69 IPV6_JOIN_GROUP = 12 70 71 IPV6_LEAVE_GROUP = 13 72 73 IPV6_MULTICAST_HOPS = 10 74 IPV6_MULTICAST_IF = 9 75 IPV6_MULTICAST_LOOP = 11 76 77 IPV6_PKTINFO = 19 78 IPV6_RECVRTHDR = 38 79 IPV6_RECVTCLASS = 40 80 IPV6_RTHDR = 32 81 IPV6_TCLASS = 39 82 83 IPV6_UNICAST_HOPS = 4 84 85 IPV6_V6ONLY = 27 86 87 IP_ADD_MEMBERSHIP = 12 88 89 IP_DROP_MEMBERSHIP = 13 90 91 IP_HDRINCL = 2 92 93 IP_MULTICAST_IF = 9 94 IP_MULTICAST_LOOP = 11 95 IP_MULTICAST_TTL = 10 96 97 IP_OPTIONS = 1 98 IP_RECVDSTADDR = 25 99 IP_TOS = 3 100 IP_TTL = 4 101 102 MSG_BCAST = 1024 103 MSG_CTRUNC = 512 104 MSG_DONTROUTE = 4 105 MSG_ERRQUEUE = 4096 106 MSG_MCAST = 2048 107 MSG_OOB = 1 108 MSG_PEEK = 2 109 MSG_TRUNC = 256 110 MSG_WAITALL = 8 111 112 NI_DGRAM = 16 113 NI_MAXHOST = 1025 114 NI_MAXSERV = 32 115 NI_NAMEREQD = 4 116 NI_NOFQDN = 1 117 NI_NUMERICHOST = 2 118 NI_NUMERICSERV = 8 119 120 RCVALL_MAX = 3 121 RCVALL_OFF = 0 122 RCVALL_ON = 1 123 RCVALL_SOCKETLEVELONLY = 2 124 125 SHUT_RD = 0 126 SHUT_RDWR = 2 127 SHUT_WR = 1 128 129 SIO_KEEPALIVE_VALS = 2550136836 130 131 SIO_LOOPBACK_FAST_PATH = 2550136848 132 133 SIO_RCVALL = 2550136833 134 135 SOCK_DGRAM = 2 136 SOCK_RAW = 3 137 SOCK_RDM = 4 138 SOCK_SEQPACKET = 5 139 SOCK_STREAM = 1 140 141 SOL_IP = 0 142 SOL_SOCKET = 65535 143 SOL_TCP = 6 144 SOL_UDP = 17 145 146 SOMAXCONN = 2147483647 147 SO_ACCEPTCONN = 2 148 SO_BROADCAST = 32 149 SO_DEBUG = 1 150 SO_DONTROUTE = 16 151 SO_ERROR = 4103 152 SO_EXCLUSIVEADDRUSE = -5 153 SO_KEEPALIVE = 8 154 SO_LINGER = 128 155 SO_OOBINLINE = 256 156 SO_RCVBUF = 4098 157 SO_RCVLOWAT = 4100 158 SO_RCVTIMEO = 4102 159 SO_REUSEADDR = 4 160 SO_SNDBUF = 4097 161 SO_SNDLOWAT = 4099 162 SO_SNDTIMEO = 4101 163 SO_TYPE = 4104 164 SO_USELOOPBACK = 64 165 166 TCP_FASTOPEN = 15 167 TCP_KEEPCNT = 16 168 TCP_KEEPIDLE = 3 169 TCP_KEEPINTVL = 17 170 TCP_MAXSEG = 4 171 TCP_NODELAY = 1 172 173 # functions 174 175 def close(integer): # real signature unknown; restored from __doc__ 176 """ 177 close(integer) -> None 178 179 Close an integer socket file descriptor. This is like os.close(), but for 180 sockets; on some platforms os.close() won't work for socket file descriptors. 181 """ 182 pass 183 184 def dup(integer): # real signature unknown; restored from __doc__ 185 """ 186 dup(integer) -> integer 187 188 Duplicate an integer socket file descriptor. This is like os.dup(), but for 189 sockets; on some platforms os.dup() won't work for socket file descriptors. 190 """ 191 return 0 192 193 def getaddrinfo(host, port, family=None, type=None, proto=None, flags=None): # real signature unknown; restored from __doc__ 194 """ 195 getaddrinfo(host, port [, family, type, proto, flags]) 196 -> list of (family, type, proto, canonname, sockaddr) 197 198 Resolve host and port into addrinfo struct. 199 """ 200 return [] 201 202 def getdefaulttimeout(): # real signature unknown; restored from __doc__ 203 """ 204 getdefaulttimeout() -> timeout 205 206 Returns the default timeout in seconds (float) for new socket objects. 207 A value of None indicates that new socket objects have no timeout. 208 When the socket module is first imported, the default is None. 209 """ 210 return timeout 211 212 def gethostbyaddr(host): # real signature unknown; restored from __doc__ 213 """ 214 gethostbyaddr(host) -> (name, aliaslist, addresslist) 215 216 Return the true host name, a list of aliases, and a list of IP addresses, 217 for a host. The host argument is a string giving a host name or IP number. 218 """ 219 pass 220 221 def gethostbyname(host): # real signature unknown; restored from __doc__ 222 """ 223 gethostbyname(host) -> address 224 225 Return the IP address (a string of the form '255.255.255.255') for a host. 226 """ 227 pass 228 229 def gethostbyname_ex(host): # real signature unknown; restored from __doc__ 230 """ 231 gethostbyname_ex(host) -> (name, aliaslist, addresslist) 232 233 Return the true host name, a list of aliases, and a list of IP addresses, 234 for a host. The host argument is a string giving a host name or IP number. 235 """ 236 pass 237 238 def gethostname(): # real signature unknown; restored from __doc__ 239 """ 240 gethostname() -> string 241 242 Return the current host name. 243 """ 244 return "" 245 246 def getnameinfo(sockaddr, flags): # real signature unknown; restored from __doc__ 247 """ 248 getnameinfo(sockaddr, flags) --> (host, port) 249 250 Get host and port for a sockaddr. 251 """ 252 pass 253 254 def getprotobyname(name): # real signature unknown; restored from __doc__ 255 """ 256 getprotobyname(name) -> integer 257 258 Return the protocol number for the named protocol. (Rarely used.) 259 """ 260 return 0 261 262 def getservbyname(servicename, protocolname=None): # real signature unknown; restored from __doc__ 263 """ 264 getservbyname(servicename[, protocolname]) -> integer 265 266 Return a port number from a service name and protocol name. 267 The optional protocol name, if given, should be 'tcp' or 'udp', 268 otherwise any protocol will match. 269 """ 270 return 0 271 272 def getservbyport(port, protocolname=None): # real signature unknown; restored from __doc__ 273 """ 274 getservbyport(port[, protocolname]) -> string 275 276 Return the service name from a port number and protocol name. 277 The optional protocol name, if given, should be 'tcp' or 'udp', 278 otherwise any protocol will match. 279 """ 280 return "" 281 282 def htonl(integer): # real signature unknown; restored from __doc__ 283 """ 284 htonl(integer) -> integer 285 286 Convert a 32-bit integer from host to network byte order. 287 """ 288 return 0 289 290 def htons(integer): # real signature unknown; restored from __doc__ 291 """ 292 htons(integer) -> integer 293 294 Convert a 16-bit unsigned integer from host to network byte order. 295 Note that in case the received integer does not fit in 16-bit unsigned 296 integer, but does fit in a positive C int, it is silently truncated to 297 16-bit unsigned integer. 298 However, this silent truncation feature is deprecated, and will raise an 299 exception in future versions of Python. 300 """ 301 return 0 302 303 def inet_aton(string): # real signature unknown; restored from __doc__ 304 """ 305 inet_aton(string) -> bytes giving packed 32-bit IP representation 306 307 Convert an IP address in string format (123.45.67.89) to the 32-bit packed 308 binary format used in low-level network functions. 309 """ 310 return b"" 311 312 def inet_ntoa(packed_ip): # real signature unknown; restored from __doc__ 313 """ 314 inet_ntoa(packed_ip) -> ip_address_string 315 316 Convert an IP address from 32-bit packed binary format to string format 317 """ 318 pass 319 320 def inet_ntop(af, packed_ip): # real signature unknown; restored from __doc__ 321 """ 322 inet_ntop(af, packed_ip) -> string formatted IP address 323 324 Convert a packed IP address of the given family to string format. 325 """ 326 return "" 327 328 def inet_pton(af, ip): # real signature unknown; restored from __doc__ 329 """ 330 inet_pton(af, ip) -> packed IP address string 331 332 Convert an IP address from string format to a packed string suitable 333 for use with low-level network functions. 334 """ 335 pass 336 337 def ntohl(integer): # real signature unknown; restored from __doc__ 338 """ 339 ntohl(integer) -> integer 340 341 Convert a 32-bit integer from network to host byte order. 342 """ 343 return 0 344 345 def ntohs(integer): # real signature unknown; restored from __doc__ 346 """ 347 ntohs(integer) -> integer 348 349 Convert a 16-bit unsigned integer from network to host byte order. 350 Note that in case the received integer does not fit in 16-bit unsigned 351 integer, but does fit in a positive C int, it is silently truncated to 352 16-bit unsigned integer. 353 However, this silent truncation feature is deprecated, and will raise an 354 exception in future versions of Python. 355 """ 356 return 0 357 358 def setdefaulttimeout(timeout): # real signature unknown; restored from __doc__ 359 """ 360 setdefaulttimeout(timeout) 361 362 Set the default timeout in seconds (float) for new socket objects. 363 A value of None indicates that new socket objects have no timeout. 364 When the socket module is first imported, the default is None. 365 """ 366 pass 367 368 # classes 369 370 class error(Exception): 371 """ Base class for I/O related errors. """ 372 def __init__(self, *args, **kwargs): # real signature unknown 373 pass 374 375 @staticmethod # known case of __new__ 376 def __new__(*args, **kwargs): # real signature unknown 377 """ Create and return a new object. See help(type) for accurate signature. """ 378 pass 379 380 def __reduce__(self, *args, **kwargs): # real signature unknown 381 pass 382 383 def __str__(self, *args, **kwargs): # real signature unknown 384 """ Return str(self). """ 385 pass 386 387 characters_written = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 388 389 errno = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 390 """POSIX exception code""" 391 392 filename = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 393 """exception filename""" 394 395 filename2 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 396 """second exception filename""" 397 398 strerror = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 399 """exception strerror""" 400 401 winerror = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 402 """Win32 exception code""" 403 404 405 406 class gaierror(OSError): 407 # no doc 408 def __init__(self, *args, **kwargs): # real signature unknown 409 pass 410 411 __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 412 """list of weak references to the object (if defined)""" 413 414 415 416 class herror(OSError): 417 # no doc 418 def __init__(self, *args, **kwargs): # real signature unknown 419 pass 420 421 __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 422 """list of weak references to the object (if defined)""" 423 424 425 426 class SocketType(object): 427 """ 428 socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object 429 socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object 430 431 Open a socket of the given type. The family argument specifies the 432 address family; it defaults to AF_INET. The type argument specifies 433 whether this is a stream (SOCK_STREAM, this is the default) 434 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0, 435 specifying the default protocol. Keyword arguments are accepted. 436 The socket is created as non-inheritable. 437 438 When a fileno is passed in, family, type and proto are auto-detected, 439 unless they are explicitly set. 440 441 A socket object represents one endpoint of a network connection. 442 443 Methods of socket objects (keyword arguments not allowed): 444 445 _accept() -- accept connection, returning new socket fd and client address 446 bind(addr) -- bind the socket to a local address 447 close() -- close the socket 448 connect(addr) -- connect the socket to a remote address 449 connect_ex(addr) -- connect, return an error code instead of an exception 450 dup() -- return a new socket fd duplicated from fileno() 451 fileno() -- return underlying file descriptor 452 getpeername() -- return remote address [*] 453 getsockname() -- return local address 454 getsockopt(level, optname[, buflen]) -- get socket options 455 gettimeout() -- return timeout or None 456 listen([n]) -- start listening for incoming connections 457 recv(buflen[, flags]) -- receive data 458 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer) 459 recvfrom(buflen[, flags]) -- receive data and sender's address 460 recvfrom_into(buffer[, nbytes, [, flags]) 461 -- receive data and sender's address (into a buffer) 462 sendall(data[, flags]) -- send all data 463 send(data[, flags]) -- send data, may not send all of it 464 sendto(data[, flags], addr) -- send data to a given address 465 setblocking(0 | 1) -- set or clear the blocking I/O flag 466 getblocking() -- return True if socket is blocking, False if non-blocking 467 setsockopt(level, optname, value[, optlen]) -- set socket options 468 settimeout(None | float) -- set or clear the timeout 469 shutdown(how) -- shut down traffic in one or both directions 470 if_nameindex() -- return all network interface indices and names 471 if_nametoindex(name) -- return the corresponding interface index 472 if_indextoname(index) -- return the corresponding interface name 473 474 [*] not available on all platforms! 475 """ 476 def bind(self, address): # real signature unknown; restored from __doc__ 477 """ 478 bind(address) 479 480 Bind the socket to a local address. For IP sockets, the address is a 481 pair (host, port); the host must refer to the local host. For raw packet 482 sockets the address is a tuple (ifname, proto [,pkttype [,hatype [,addr]]]) 483 """ 484 pass 485 486 def close(self): # real signature unknown; restored from __doc__ 487 """ 488 close() 489 490 Close the socket. It cannot be used after this call. 491 """ 492 pass 493 494 def connect(self, address): # real signature unknown; restored from __doc__ 495 """ 496 connect(address) 497 498 Connect the socket to a remote address. For IP sockets, the address 499 is a pair (host, port). 500 """ 501 pass 502 503 def connect_ex(self, address): # real signature unknown; restored from __doc__ 504 """ 505 connect_ex(address) -> errno 506 507 This is like connect(address), but returns an error code (the errno value) 508 instead of raising an exception when an error occurs. 509 """ 510 pass 511 512 def detach(self): # real signature unknown; restored from __doc__ 513 """ 514 detach() 515 516 Close the socket object without closing the underlying file descriptor. 517 The object cannot be used after this call, but the file descriptor 518 can be reused for other purposes. The file descriptor is returned. 519 """ 520 pass 521 522 def fileno(self): # real signature unknown; restored from __doc__ 523 """ 524 fileno() -> integer 525 526 Return the integer file descriptor of the socket. 527 """ 528 return 0 529 530 def getblocking(self): # real signature unknown; restored from __doc__ 531 """ 532 getblocking() 533 534 Returns True if socket is in blocking mode, or False if it 535 is in non-blocking mode. 536 """ 537 pass 538 539 def getpeername(self): # real signature unknown; restored from __doc__ 540 """ 541 getpeername() -> address info 542 543 Return the address of the remote endpoint. For IP sockets, the address 544 info is a pair (hostaddr, port). 545 """ 546 pass 547 548 def getsockname(self): # real signature unknown; restored from __doc__ 549 """ 550 getsockname() -> address info 551 552 Return the address of the local endpoint. For IP sockets, the address 553 info is a pair (hostaddr, port). 554 """ 555 pass 556 557 def getsockopt(self, level, option, buffersize=None): # real signature unknown; restored from __doc__ 558 """ 559 getsockopt(level, option[, buffersize]) -> value 560 561 Get a socket option. See the Unix manual for level and option. 562 If a nonzero buffersize argument is given, the return value is a 563 string of that length; otherwise it is an integer. 564 """ 565 pass 566 567 def gettimeout(self): # real signature unknown; restored from __doc__ 568 """ 569 gettimeout() -> timeout 570 571 Returns the timeout in seconds (float) associated with socket 572 operations. A timeout of None indicates that timeouts on socket 573 operations are disabled. 574 """ 575 return timeout 576 577 def ioctl(self, cmd, option): # real signature unknown; restored from __doc__ 578 """ 579 ioctl(cmd, option) -> long 580 581 Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are 582 SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants. 583 SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval). 584 SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default 585 """ 586 return 0 587 588 def listen(self, backlog=None): # real signature unknown; restored from __doc__ 589 """ 590 listen([backlog]) 591 592 Enable a server to accept connections. If backlog is specified, it must be 593 at least 0 (if it is lower, it is set to 0); it specifies the number of 594 unaccepted connections that the system will allow before refusing new 595 connections. If not specified, a default reasonable value is chosen. 596 """ 597 pass 598 599 def recv(self, buffersize, flags=None): # real signature unknown; restored from __doc__ 600 """ 601 recv(buffersize[, flags]) -> data 602 603 Receive up to buffersize bytes from the socket. For the optional flags 604 argument, see the Unix manual. When no data is available, block until 605 at least one byte is available or until the remote end is closed. When 606 the remote end is closed and all data is read, return the empty string. 607 """ 608 pass 609 610 def recvfrom(self, buffersize, flags=None): # real signature unknown; restored from __doc__ 611 """ 612 recvfrom(buffersize[, flags]) -> (data, address info) 613 614 Like recv(buffersize, flags) but also return the sender's address info. 615 """ 616 pass 617 618 def recvfrom_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__ 619 """ 620 recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info) 621 622 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info. 623 """ 624 pass 625 626 def recv_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__ 627 """ 628 recv_into(buffer, [nbytes[, flags]]) -> nbytes_read 629 630 A version of recv() that stores its data into a buffer rather than creating 631 a new string. Receive up to buffersize bytes from the socket. If buffersize 632 is not specified (or 0), receive up to the size available in the given buffer. 633 634 See recv() for documentation about the flags. 635 """ 636 pass 637 638 def send(self, data, flags=None): # real signature unknown; restored from __doc__ 639 """ 640 send(data[, flags]) -> count 641 642 Send a data string to the socket. For the optional flags 643 argument, see the Unix manual. Return the number of bytes 644 sent; this may be less than len(data) if the network is busy. 645 """ 646 pass 647 648 def sendall(self, data, flags=None): # real signature unknown; restored from __doc__ 649 """ 650 sendall(data[, flags]) 651 652 Send a data string to the socket. For the optional flags 653 argument, see the Unix manual. This calls send() repeatedly 654 until all data is sent. If an error occurs, it's impossible 655 to tell how much data has been sent. 656 """ 657 pass 658 659 def sendto(self, data, flags=None, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 660 """ 661 sendto(data[, flags], address) -> count 662 663 Like send(data, flags) but allows specifying the destination address. 664 For IP sockets, the address is a pair (hostaddr, port). 665 """ 666 pass 667 668 def setblocking(self, flag): # real signature unknown; restored from __doc__ 669 """ 670 setblocking(flag) 671 672 Set the socket to blocking (flag is true) or non-blocking (false). 673 setblocking(True) is equivalent to settimeout(None); 674 setblocking(False) is equivalent to settimeout(0.0). 675 """ 676 pass 677 678 def setsockopt(self, level, option, value): # real signature unknown; restored from __doc__ 679 """ 680 setsockopt(level, option, value: int) 681 setsockopt(level, option, value: buffer) 682 setsockopt(level, option, None, optlen: int) 683 684 Set a socket option. See the Unix manual for level and option. 685 The value argument can either be an integer, a string buffer, or 686 None, optlen. 687 """ 688 pass 689 690 def settimeout(self, timeout): # real signature unknown; restored from __doc__ 691 """ 692 settimeout(timeout) 693 694 Set a timeout on socket operations. 'timeout' can be a float, 695 giving in seconds, or None. Setting a timeout of None disables 696 the timeout feature and is equivalent to setblocking(1). 697 Setting a timeout of zero is the same as setblocking(0). 698 """ 699 pass 700 701 def share(self, process_id): # real signature unknown; restored from __doc__ 702 """ 703 share(process_id) -> bytes 704 705 Share the socket with another process. The target process id 706 must be provided and the resulting bytes object passed to the target 707 process. There the shared socket can be instantiated by calling 708 socket.fromshare(). 709 """ 710 return b"" 711 712 def shutdown(self, flag): # real signature unknown; restored from __doc__ 713 """ 714 shutdown(flag) 715 716 Shut down the reading side of the socket (flag == SHUT_RD), the writing side 717 of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR). 718 """ 719 pass 720 721 def _accept(self): # real signature unknown; restored from __doc__ 722 """ 723 _accept() -> (integer, address info) 724 725 Wait for an incoming connection. Return a new socket file descriptor 726 representing the connection, and the address of the client. 727 For IP sockets, the address info is a pair (hostaddr, port). 728 """ 729 pass 730 731 def __del__(self, *args, **kwargs): # real signature unknown 732 pass 733 734 def __getattribute__(self, *args, **kwargs): # real signature unknown 735 """ Return getattr(self, name). """ 736 pass 737 738 def __init__(self, *args, **kwargs): # real signature unknown 739 pass 740 741 @staticmethod # known case of __new__ 742 def __new__(*args, **kwargs): # real signature unknown 743 """ Create and return a new object. See help(type) for accurate signature. """ 744 pass 745 746 def __repr__(self, *args, **kwargs): # real signature unknown 747 """ Return repr(self). """ 748 pass 749 750 family = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 751 """the socket family""" 752 753 proto = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 754 """the socket protocol""" 755 756 timeout = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 757 """the socket timeout""" 758 759 type = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 760 """the socket type""" 761 762 763 764 socket = SocketType 765 766 767 class timeout(OSError): 768 # no doc 769 def __init__(self, *args, **kwargs): # real signature unknown 770 pass 771 772 __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 773 """list of weak references to the object (if defined)""" 774 775 776 777 # variables with complex values 778 779 CAPI = None # (!) real value is '<capsule object "_socket.CAPI" at 0x00000207994EBD20>' 780 781 __loader__ = None # (!) real value is '<_frozen_importlib_external.ExtensionFileLoader object at 0x000002079944B2B0>' 782 783 __spec__ = None # (!) real value is "ModuleSpec(name='_socket', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x000002079944B2B0>, origin='C:\\\\BuildAgent\\\\system\\\\.persistent_cache\\\\pycharm\\\\pythons4skeletons\\\\python37\\\\DLLs\\\\_socket.pyd')"
socketserver.py

1 """Generic socket server classes. 2 3 This module tries to capture the various aspects of defining a server: 4 5 For socket-based servers: 6 7 - address family: 8 - AF_INET{,6}: IP (Internet Protocol) sockets (default) 9 - AF_UNIX: Unix domain sockets 10 - others, e.g. AF_DECNET are conceivable (see <socket.h> 11 - socket type: 12 - SOCK_STREAM (reliable stream, e.g. TCP) 13 - SOCK_DGRAM (datagrams, e.g. UDP) 14 15 For request-based servers (including socket-based): 16 17 - client address verification before further looking at the request 18 (This is actually a hook for any processing that needs to look 19 at the request before anything else, e.g. logging) 20 - how to handle multiple requests: 21 - synchronous (one request is handled at a time) 22 - forking (each request is handled by a new process) 23 - threading (each request is handled by a new thread) 24 25 The classes in this module favor the server type that is simplest to 26 write: a synchronous TCP/IP server. This is bad class design, but 27 save some typing. (There's also the issue that a deep class hierarchy 28 slows down method lookups.) 29 30 There are five classes in an inheritance diagram, four of which represent 31 synchronous servers of four types: 32 33 +------------+ 34 | BaseServer | 35 +------------+ 36 | 37 v 38 +-----------+ +------------------+ 39 | TCPServer |------->| UnixStreamServer | 40 +-----------+ +------------------+ 41 | 42 v 43 +-----------+ +--------------------+ 44 | UDPServer |------->| UnixDatagramServer | 45 +-----------+ +--------------------+ 46 47 Note that UnixDatagramServer derives from UDPServer, not from 48 UnixStreamServer -- the only difference between an IP and a Unix 49 stream server is the address family, which is simply repeated in both 50 unix server classes. 51 52 Forking and threading versions of each type of server can be created 53 using the ForkingMixIn and ThreadingMixIn mix-in classes. For 54 instance, a threading UDP server class is created as follows: 55 56 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass 57 58 The Mix-in class must come first, since it overrides a method defined 59 in UDPServer! Setting the various member variables also changes 60 the behavior of the underlying server mechanism. 61 62 To implement a service, you must derive a class from 63 BaseRequestHandler and redefine its handle() method. You can then run 64 various versions of the service by combining one of the server classes 65 with your request handler class. 66 67 The request handler class must be different for datagram or stream 68 services. This can be hidden by using the request handler 69 subclasses StreamRequestHandler or DatagramRequestHandler. 70 71 Of course, you still have to use your head! 72 73 For instance, it makes no sense to use a forking server if the service 74 contains state in memory that can be modified by requests (since the 75 modifications in the child process would never reach the initial state 76 kept in the parent process and passed to each child). In this case, 77 you can use a threading server, but you will probably have to use 78 locks to avoid two requests that come in nearly simultaneous to apply 79 conflicting changes to the server state. 80 81 On the other hand, if you are building e.g. an HTTP server, where all 82 data is stored externally (e.g. in the file system), a synchronous 83 class will essentially render the service "deaf" while one request is 84 being handled -- which may be for a very long time if a client is slow 85 to read all the data it has requested. Here a threading or forking 86 server is appropriate. 87 88 In some cases, it may be appropriate to process part of a request 89 synchronously, but to finish processing in a forked child depending on 90 the request data. This can be implemented by using a synchronous 91 server and doing an explicit fork in the request handler class 92 handle() method. 93 94 Another approach to handling multiple simultaneous requests in an 95 environment that supports neither threads nor fork (or where these are 96 too expensive or inappropriate for the service) is to maintain an 97 explicit table of partially finished requests and to use a selector to 98 decide which request to work on next (or whether to handle a new 99 incoming request). This is particularly important for stream services 100 where each client can potentially be connected for a long time (if 101 threads or subprocesses cannot be used). 102 103 Future work: 104 - Standard classes for Sun RPC (which uses either UDP or TCP) 105 - Standard mix-in classes to implement various authentication 106 and encryption schemes 107 108 XXX Open problems: 109 - What to do with out-of-band data? 110 111 BaseServer: 112 - split generic "request" functionality out into BaseServer class. 113 Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org> 114 115 example: read entries from a SQL database (requires overriding 116 get_request() to return a table entry from the database). 117 entry is processed by a RequestHandlerClass. 118 119 """ 120 121 # Author of the BaseServer patch: Luke Kenneth Casson Leighton 122 123 __version__ = "0.4" 124 125 126 import socket 127 import selectors 128 import os 129 import sys 130 import threading 131 from io import BufferedIOBase 132 from time import monotonic as time 133 134 __all__ = ["BaseServer", "TCPServer", "UDPServer", 135 "ThreadingUDPServer", "ThreadingTCPServer", 136 "BaseRequestHandler", "StreamRequestHandler", 137 "DatagramRequestHandler", "ThreadingMixIn"] 138 if hasattr(os, "fork"): 139 __all__.extend(["ForkingUDPServer","ForkingTCPServer", "ForkingMixIn"]) 140 if hasattr(socket, "AF_UNIX"): 141 __all__.extend(["UnixStreamServer","UnixDatagramServer", 142 "ThreadingUnixStreamServer", 143 "ThreadingUnixDatagramServer"]) 144 145 # poll/select have the advantage of not requiring any extra file descriptor, 146 # contrarily to epoll/kqueue (also, they require a single syscall). 147 if hasattr(selectors, 'PollSelector'): 148 _ServerSelector = selectors.PollSelector 149 else: 150 _ServerSelector = selectors.SelectSelector 151 152 153 class BaseServer: 154 155 """Base class for server classes. 156 157 Methods for the caller: 158 159 - __init__(server_address, RequestHandlerClass) 160 - serve_forever(poll_interval=0.5) 161 - shutdown() 162 - handle_request() # if you do not use serve_forever() 163 - fileno() -> int # for selector 164 165 Methods that may be overridden: 166 167 - server_bind() 168 - server_activate() 169 - get_request() -> request, client_address 170 - handle_timeout() 171 - verify_request(request, client_address) 172 - server_close() 173 - process_request(request, client_address) 174 - shutdown_request(request) 175 - close_request(request) 176 - service_actions() 177 - handle_error() 178 179 Methods for derived classes: 180 181 - finish_request(request, client_address) 182 183 Class variables that may be overridden by derived classes or 184 instances: 185 186 - timeout 187 - address_family 188 - socket_type 189 - allow_reuse_address 190 191 Instance variables: 192 193 - RequestHandlerClass 194 - socket 195 196 """ 197 198 timeout = None 199 200 def __init__(self, server_address, RequestHandlerClass): 201 """Constructor. May be extended, do not override.""" 202 self.server_address = server_address 203 self.RequestHandlerClass = RequestHandlerClass 204 self.__is_shut_down = threading.Event() 205 self.__shutdown_request = False 206 207 def server_activate(self): 208 """Called by constructor to activate the server. 209 210 May be overridden. 211 212 """ 213 pass 214 215 def serve_forever(self, poll_interval=0.5): 216 """Handle one request at a time until shutdown. 217 218 Polls for shutdown every poll_interval seconds. Ignores 219 self.timeout. If you need to do periodic tasks, do them in 220 another thread. 221 """ 222 self.__is_shut_down.clear() 223 try: 224 # XXX: Consider using another file descriptor or connecting to the 225 # socket to wake this up instead of polling. Polling reduces our 226 # responsiveness to a shutdown request and wastes cpu at all other 227 # times. 228 with _ServerSelector() as selector: 229 selector.register(self, selectors.EVENT_READ) 230 231 while not self.__shutdown_request: 232 ready = selector.select(poll_interval) 233 # bpo-35017: shutdown() called during select(), exit immediately. 234 if self.__shutdown_request: 235 break 236 if ready: 237 self._handle_request_noblock() 238 239 self.service_actions() 240 finally: 241 self.__shutdown_request = False 242 self.__is_shut_down.set() 243 244 def shutdown(self): 245 """Stops the serve_forever loop. 246 247 Blocks until the loop has finished. This must be called while 248 serve_forever() is running in another thread, or it will 249 deadlock. 250 """ 251 self.__shutdown_request = True 252 self.__is_shut_down.wait() 253 254 def service_actions(self): 255 """Called by the serve_forever() loop. 256 257 May be overridden by a subclass / Mixin to implement any code that 258 needs to be run during the loop. 259 """ 260 pass 261 262 # The distinction between handling, getting, processing and finishing a 263 # request is fairly arbitrary. Remember: 264 # 265 # - handle_request() is the top-level call. It calls selector.select(), 266 # get_request(), verify_request() and process_request() 267 # - get_request() is different for stream or datagram sockets 268 # - process_request() is the place that may fork a new process or create a 269 # new thread to finish the request 270 # - finish_request() instantiates the request handler class; this 271 # constructor will handle the request all by itself 272 273 def handle_request(self): 274 """Handle one request, possibly blocking. 275 276 Respects self.timeout. 277 """ 278 # Support people who used socket.settimeout() to escape 279 # handle_request before self.timeout was available. 280 timeout = self.socket.gettimeout() 281 if timeout is None: 282 timeout = self.timeout 283 elif self.timeout is not None: 284 timeout = min(timeout, self.timeout) 285 if timeout is not None: 286 deadline = time() + timeout 287 288 # Wait until a request arrives or the timeout expires - the loop is 289 # necessary to accommodate early wakeups due to EINTR. 290 with _ServerSelector() as selector: 291 selector.register(self, selectors.EVENT_READ) 292 293 while True: 294 ready = selector.select(timeout) 295 if ready: 296 return self._handle_request_noblock() 297 else: 298 if timeout is not None: 299 timeout = deadline - time() 300 if timeout < 0: 301 return self.handle_timeout() 302 303 def _handle_request_noblock(self): 304 """Handle one request, without blocking. 305 306 I assume that selector.select() has returned that the socket is 307 readable before this function was called, so there should be no risk of 308 blocking in get_request(). 309 """ 310 try: 311 request, client_address = self.get_request() 312 except OSError: 313 return 314 if self.verify_request(request, client_address): 315 try: 316 self.process_request(request, client_address) 317 except Exception: 318 self.handle_error(request, client_address) 319 self.shutdown_request(request) 320 except: 321 self.shutdown_request(request) 322 raise 323 else: 324 self.shutdown_request(request) 325 326 def handle_timeout(self): 327 """Called if no new request arrives within self.timeout. 328 329 Overridden by ForkingMixIn. 330 """ 331 pass 332 333 def verify_request(self, request, client_address): 334 """Verify the request. May be overridden. 335 336 Return True if we should proceed with this request. 337 338 """ 339 return True 340 341 def process_request(self, request, client_address): 342 """Call finish_request. 343 344 Overridden by ForkingMixIn and ThreadingMixIn. 345 346 """ 347 self.finish_request(request, client_address) 348 self.shutdown_request(request) 349 350 def server_close(self): 351 """Called to clean-up the server. 352 353 May be overridden. 354 355 """ 356 pass 357 358 def finish_request(self, request, client_address): 359 """Finish one request by instantiating RequestHandlerClass.""" 360 self.RequestHandlerClass(request, client_address, self) 361 362 def shutdown_request(self, request): 363 """Called to shutdown and close an individual request.""" 364 self.close_request(request) 365 366 def close_request(self, request): 367 """Called to clean up an individual request.""" 368 pass 369 370 def handle_error(self, request, client_address): 371 """Handle an error gracefully. May be overridden. 372 373 The default is to print a traceback and continue. 374 375 """ 376 print('-'*40, file=sys.stderr) 377 print('Exception happened during processing of request from', 378 client_address, file=sys.stderr) 379 import traceback 380 traceback.print_exc() 381 print('-'*40, file=sys.stderr) 382 383 def __enter__(self): 384 return self 385 386 def __exit__(self, *args): 387 self.server_close() 388 389 390 class TCPServer(BaseServer): 391 392 """Base class for various socket-based server classes. 393 394 Defaults to synchronous IP stream (i.e., TCP). 395 396 Methods for the caller: 397 398 - __init__(server_address, RequestHandlerClass, bind_and_activate=True) 399 - serve_forever(poll_interval=0.5) 400 - shutdown() 401 - handle_request() # if you don't use serve_forever() 402 - fileno() -> int # for selector 403 404 Methods that may be overridden: 405 406 - server_bind() 407 - server_activate() 408 - get_request() -> request, client_address 409 - handle_timeout() 410 - verify_request(request, client_address) 411 - process_request(request, client_address) 412 - shutdown_request(request) 413 - close_request(request) 414 - handle_error() 415 416 Methods for derived classes: 417 418 - finish_request(request, client_address) 419 420 Class variables that may be overridden by derived classes or 421 instances: 422 423 - timeout 424 - address_family 425 - socket_type 426 - request_queue_size (only for stream sockets) 427 - allow_reuse_address 428 429 Instance variables: 430 431 - server_address 432 - RequestHandlerClass 433 - socket 434 435 """ 436 437 address_family = socket.AF_INET 438 439 socket_type = socket.SOCK_STREAM 440 441 request_queue_size = 5 442 443 allow_reuse_address = False 444 445 def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): 446 """Constructor. May be extended, do not override.""" 447 BaseServer.__init__(self, server_address, RequestHandlerClass) 448 self.socket = socket.socket(self.address_family, 449 self.socket_type) 450 if bind_and_activate: 451 try: 452 self.server_bind() 453 self.server_activate() 454 except: 455 self.server_close() 456 raise 457 458 def server_bind(self): 459 """Called by constructor to bind the socket. 460 461 May be overridden. 462 463 """ 464 if self.allow_reuse_address: 465 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 466 self.socket.bind(self.server_address) 467 self.server_address = self.socket.getsockname() 468 469 def server_activate(self): 470 """Called by constructor to activate the server. 471 472 May be overridden. 473 474 """ 475 self.socket.listen(self.request_queue_size) 476 477 def server_close(self): 478 """Called to clean-up the server. 479 480 May be overridden. 481 482 """ 483 self.socket.close() 484 485 def fileno(self): 486 """Return socket file number. 487 488 Interface required by selector. 489 490 """ 491 return self.socket.fileno() 492 493 def get_request(self): 494 """Get the request and client address from the socket. 495 496 May be overridden. 497 498 """ 499 return self.socket.accept() 500 501 def shutdown_request(self, request): 502 """Called to shutdown and close an individual request.""" 503 try: 504 #explicitly shutdown. socket.close() merely releases 505 #the socket and waits for GC to perform the actual close. 506 request.shutdown(socket.SHUT_WR) 507 except OSError: 508 pass #some platforms may raise ENOTCONN here 509 self.close_request(request) 510 511 def close_request(self, request): 512 """Called to clean up an individual request.""" 513 request.close() 514 515 516 class UDPServer(TCPServer): 517 518 """UDP server class.""" 519 520 allow_reuse_address = False 521 522 socket_type = socket.SOCK_DGRAM 523 524 max_packet_size = 8192 525 526 def get_request(self): 527 data, client_addr = self.socket.recvfrom(self.max_packet_size) 528 return (data, self.socket), client_addr 529 530 def server_activate(self): 531 # No need to call listen() for UDP. 532 pass 533 534 def shutdown_request(self, request): 535 # No need to shutdown anything. 536 self.close_request(request) 537 538 def close_request(self, request): 539 # No need to close anything. 540 pass 541 542 if hasattr(os, "fork"): 543 class ForkingMixIn: 544 """Mix-in class to handle each request in a new process.""" 545 546 timeout = 300 547 active_children = None 548 max_children = 40 549 # If true, server_close() waits until all child processes complete. 550 block_on_close = True 551 552 def collect_children(self, *, blocking=False): 553 """Internal routine to wait for children that have exited.""" 554 if self.active_children is None: 555 return 556 557 # If we're above the max number of children, wait and reap them until 558 # we go back below threshold. Note that we use waitpid(-1) below to be 559 # able to collect children in size(<defunct children>) syscalls instead 560 # of size(<children>): the downside is that this might reap children 561 # which we didn't spawn, which is why we only resort to this when we're 562 # above max_children. 563 while len(self.active_children) >= self.max_children: 564 try: 565 pid, _ = os.waitpid(-1, 0) 566 self.active_children.discard(pid) 567 except ChildProcessError: 568 # we don't have any children, we're done 569 self.active_children.clear() 570 except OSError: 571 break 572 573 # Now reap all defunct children. 574 for pid in self.active_children.copy(): 575 try: 576 flags = 0 if blocking else os.WNOHANG 577 pid, _ = os.waitpid(pid, flags) 578 # if the child hasn't exited yet, pid will be 0 and ignored by 579 # discard() below 580 self.active_children.discard(pid) 581 except ChildProcessError: 582 # someone else reaped it 583 self.active_children.discard(pid) 584 except OSError: 585 pass 586 587 def handle_timeout(self): 588 """Wait for zombies after self.timeout seconds of inactivity. 589 590 May be extended, do not override. 591 """ 592 self.collect_children() 593 594 def service_actions(self): 595 """Collect the zombie child processes regularly in the ForkingMixIn. 596 597 service_actions is called in the BaseServer's serve_forever loop. 598 """ 599 self.collect_children() 600 601 def process_request(self, request, client_address): 602 """Fork a new subprocess to process the request.""" 603 pid = os.fork() 604 if pid: 605 # Parent process 606 if self.active_children is None: 607 self.active_children = set() 608 self.active_children.add(pid) 609 self.close_request(request) 610 return 611 else: 612 # Child process. 613 # This must never return, hence os._exit()! 614 status = 1 615 try: 616 self.finish_request(request, client_address) 617 status = 0 618 except Exception: 619 self.handle_error(request, client_address) 620 finally: 621 try: 622 self.shutdown_request(request) 623 finally: 624 os._exit(status) 625 626 def server_close(self): 627 super().server_close() 628 self.collect_children(blocking=self.block_on_close) 629 630 631 class ThreadingMixIn: 632 """Mix-in class to handle each request in a new thread.""" 633 634 # Decides how threads will act upon termination of the 635 # main process 636 daemon_threads = False 637 # If true, server_close() waits until all non-daemonic threads terminate. 638 block_on_close = True 639 # For non-daemonic threads, list of threading.Threading objects 640 # used by server_close() to wait for all threads completion. 641 _threads = None 642 643 def process_request_thread(self, request, client_address): 644 """Same as in BaseServer but as a thread. 645 646 In addition, exception handling is done here. 647 648 """ 649 try: 650 self.finish_request(request, client_address) 651 except Exception: 652 self.handle_error(request, client_address) 653 finally: 654 self.shutdown_request(request) 655 656 def process_request(self, request, client_address): 657 """Start a new thread to process the request.""" 658 t = threading.Thread(target = self.process_request_thread, 659 args = (request, client_address)) 660 t.daemon = self.daemon_threads 661 if not t.daemon and self.block_on_close: 662 if self._threads is None: 663 self._threads = [] 664 self._threads.append(t) 665 t.start() 666 667 def server_close(self): 668 super().server_close() 669 if self.block_on_close: 670 threads = self._threads 671 self._threads = None 672 if threads: 673 for thread in threads: 674 thread.join() 675 676 677 if hasattr(os, "fork"): 678 class ForkingUDPServer(ForkingMixIn, UDPServer): pass 679 class ForkingTCPServer(ForkingMixIn, TCPServer): pass 680 681 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass 682 class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass 683 684 if hasattr(socket, 'AF_UNIX'): 685 686 class UnixStreamServer(TCPServer): 687 address_family = socket.AF_UNIX 688 689 class UnixDatagramServer(UDPServer): 690 address_family = socket.AF_UNIX 691 692 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass 693 694 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass 695 696 class BaseRequestHandler: 697 698 """Base class for request handler classes. 699 700 This class is instantiated for each request to be handled. The 701 constructor sets the instance variables request, client_address 702 and server, and then calls the handle() method. To implement a 703 specific service, all you need to do is to derive a class which 704 defines a handle() method. 705 706 The handle() method can find the request as self.request, the 707 client address as self.client_address, and the server (in case it 708 needs access to per-server information) as self.server. Since a 709 separate instance is created for each request, the handle() method 710 can define other arbitrary instance variables. 711 712 """ 713 714 def __init__(self, request, client_address, server): 715 self.request = request 716 self.client_address = client_address 717 self.server = server 718 self.setup() 719 try: 720 self.handle() 721 finally: 722 self.finish() 723 724 def setup(self): 725 pass 726 727 def handle(self): 728 pass 729 730 def finish(self): 731 pass 732 733 734 # The following two classes make it possible to use the same service 735 # class for stream or datagram servers. 736 # Each class sets up these instance variables: 737 # - rfile: a file object from which receives the request is read 738 # - wfile: a file object to which the reply is written 739 # When the handle() method returns, wfile is flushed properly 740 741 742 class StreamRequestHandler(BaseRequestHandler): 743 744 """Define self.rfile and self.wfile for stream sockets.""" 745 746 # Default buffer sizes for rfile, wfile. 747 # We default rfile to buffered because otherwise it could be 748 # really slow for large data (a getc() call per byte); we make 749 # wfile unbuffered because (a) often after a write() we want to 750 # read and we need to flush the line; (b) big writes to unbuffered 751 # files are typically optimized by stdio even when big reads 752 # aren't. 753 rbufsize = -1 754 wbufsize = 0 755 756 # A timeout to apply to the request socket, if not None. 757 timeout = None 758 759 # Disable nagle algorithm for this socket, if True. 760 # Use only when wbufsize != 0, to avoid small packets. 761 disable_nagle_algorithm = False 762 763 def setup(self): 764 self.connection = self.request 765 if self.timeout is not None: 766 self.connection.settimeout(self.timeout) 767 if self.disable_nagle_algorithm: 768 self.connection.setsockopt(socket.IPPROTO_TCP, 769 socket.TCP_NODELAY, True) 770 self.rfile = self.connection.makefile('rb', self.rbufsize) 771 if self.wbufsize == 0: 772 self.wfile = _SocketWriter(self.connection) 773 else: 774 self.wfile = self.connection.makefile('wb', self.wbufsize) 775 776 def finish(self): 777 if not self.wfile.closed: 778 try: 779 self.wfile.flush() 780 except socket.error: 781 # A final socket error may have occurred here, such as 782 # the local error ECONNABORTED. 783 pass 784 self.wfile.close() 785 self.rfile.close() 786 787 class _SocketWriter(BufferedIOBase): 788 """Simple writable BufferedIOBase implementation for a socket 789 790 Does not hold data in a buffer, avoiding any need to call flush().""" 791 792 def __init__(self, sock): 793 self._sock = sock 794 795 def writable(self): 796 return True 797 798 def write(self, b): 799 self._sock.sendall(b) 800 with memoryview(b) as view: 801 return view.nbytes 802 803 def fileno(self): 804 return self._sock.fileno() 805 806 class DatagramRequestHandler(BaseRequestHandler): 807 808 """Define self.rfile and self.wfile for datagram sockets.""" 809 810 def setup(self): 811 from io import BytesIO 812 self.packet, self.socket = self.request 813 self.rfile = BytesIO(self.packet) 814 self.wfile = BytesIO() 815 816 def finish(self): 817 self.socket.sendto(self.wfile.getvalue(), self.client_address)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了