Python socket简介

自豪地使用dir和help.
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket

>>> dir(socket.socket)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_sock', 'accept', 'bind', 'close', 'connect', 'connect_ex', 'dup', 'family', 'fileno', 'getpeername', 'getsockname', 'getsockopt', 'gettimeout', 'listen', 'makefile', 'proto', 'recv', 'recv_into', 'recvfrom', 'recvfrom_into', 'send', 'sendall', 'sendto', 'setblocking', 'setsockopt', 'settimeout', 'shutdown', 'type']

>>> help(socket.socket)

class _socketobject(__builtin__.object)
 | socket([family[, type[, proto]]]) -> socket object
 |  
 | Open a socket of the given type. The family argument specifies the
 | address family; it defaults to AF_INET. The type argument specifies
 | whether this is a stream (SOCK_STREAM, this is the default)
 | or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,
 | specifying the default protocol. Keyword arguments are accepted.
 |  
 | A socket object represents one endpoint of a network connection.
 |  
 | Methods of socket objects (keyword arguments not allowed):
 |  
 | accept() -- accept a connection, returning new socket and client address
 | bind(addr) -- bind the socket to a local address
 | close() -- close the socket
 | connect(addr) -- connect the socket to a remote address
 | connect_ex(addr) -- connect, return an error code instead of an exception
 | dup() -- return a new socket object identical to the current one [*]
 | fileno() -- return underlying file descriptor
 | getpeername() -- return remote address [*]
 | getsockname() -- return local address
 | getsockopt(level, optname[, buflen]) -- get socket options
 | gettimeout() -- return timeout or None
 | listen(n) -- start listening for incoming connections
 | makefile([mode, [bufsize]]) -- return a file object for the socket [*]
 | recv(buflen[, flags]) -- receive data
 | recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)
 | recvfrom(buflen[, flags]) -- receive data and sender's address
 | recvfrom_into(buffer[, nbytes, [, flags])
 | -- receive data and sender's address (into a buffer)
 | sendall(data[, flags]) -- send all data
 | send(data[, flags]) -- send data, may not send all of it
 | sendto(data[, flags], addr) -- send data to a given address
 | setblocking(0 | 1) -- set or clear the blocking I/O flag
 | setsockopt(level, optname, value) -- set socket options
 | settimeout(None | float) -- set or clear the timeout
 | shutdown(how) -- shut down traffic in one or both directions

>>> help(socket.getaddrinfo)

Help on built-in function getaddrinfo in module _socket:

getaddrinfo(…)
    getaddrinfo(host, port [, family, socktype, proto, flags])
        -> list of (family, socktype, proto, canonname, sockaddr)
    
    Resolve host and port into addrinfo struct.



Simple Demo:
# Echo server program
import socket

HOST ='' # Symbolic name meaning all available interfaces
PORT =50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close() 


# Echo client program
import socket

HOST ='' # The remote host
PORT =50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print'Received', repr(data)



1、setblocking(0 | 1) -- set or clear the blocking I/O flag
引用
Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0.0); s.setblocking(1) is equivalent to s.settimeout(None).

2、setsockopt(level, optname, value) -- set socket options
引用
Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module struct for a way to encode C structures as strings).

套接字机制提供两个套接字选项接口来控制套接字行为。一个用来设置,一个用来获取。(getsockopt)
3、settimeout(None | float) -- set or clear the timeout
引用
Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1).

4、shutdown(how) -- shut down traffic in one or both directions
引用
Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how is SHUT_WR, further sends are disallowed. If how isSHUT_RDWR, further sends and receives are disallowed. Depending on the platform, shutting down one half of the connection can also close the opposite half (e.g. on Mac OS X, shutdown(SHUT_WR) does not allow further reads on the other end of the connection).


资料参考:
http://docs.python.org/2/library/socket.html

你可能感兴趣的:(python)