python socket

本文介绍了使用Python实现TCP Server和Client的基本原理和代码示例,包括如何建立连接、发送和接收数据。同时讨论了从Python 2.x到Python 3.x的API变化,以及在使用socket API时遇到的小错误及其解决思路。
摘要由CSDN通过智能技术生成

一个tcp的简单server 和client


server:


from socket import *
import sys
from time import ctime



host=''
port=21567
bufsiz=1024
addr=(host,port)



tcpsersock=socket(AF_INET,SOCK_STREAM)
tcpsersock.bind(addr)
tcpsersock.listen(5)



while True:    
    	print("wating for connection..." )    
    	tcpclisock,addr=tcpsersock.accept()    
       	print '......connected from:',addr

	while True:
        
		data=tcpclisock.recv(bufsiz)
		if not data:break
		tcpclisock.send('[%s]%s'%(ctime(),data))
		print [ctime()],':',data

tcpclisock.close()
tcpsersock.close()

client:

from socket import *
import sys

host='localhost'
port=21567
bufsiz=1024
addr=(host,port)

tcpclisock=socket(AF_INET,SOCK_STREAM)
tcpclisock.connect(addr)

while True:
	data=raw_input('>')
	if not data:
		break
	tcpclisock.send(data)
	data=tcpclisock.recv(bufsiz)
	if not data:
		break
	print(data)

tcpclisock.close()














书上的例子大多是py2.x的 我用的是py3.x的


在使用send()  sendto()  sendall()   recv() recvfrom()的时候出现几个小错误  .  在网上查了好久还没找到API..仔细一想API就在  py-cmd里面....我真是笨死了...

py3.4:

class socket(_socket.socket)
 |  A subclass of _socket.socket adding the makefile() method.
 |
 |  Method resolution order:
 |      socket
 |      _socket.socket
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __enter__(self)
 |
 |  __exit__(self, *args)
 |
 |  __getstate__(self)
 |
 |  __init__(self, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_S
AM: 1>, proto=0, fileno=None)
 |
 |  __repr__(self)
 |      Wrap __repr__() to reveal the real class name and socket
 |      address(es).
 |
 |  accept(self)
 |      accept() -> (socket object, address info)
 |
 |      Wait for an incoming connection.  Return a new socket
 |      representing the connection, and the address of the client.
 |      For IP sockets, the address info is a pair (hostaddr, port).
 |
 |  close(self)
 |
 |  detach(self)
 |      detach() -> file descriptor
 |
 |      Close the socket object without closing the underlying file descripto
 |      The object cannot be used after this call, but the file descriptor
 |      can be reused for other purposes.  The file descriptor is returned.
 |
 |  dup(self)
 |      dup() -> socket object
 |
 |      Duplicate the socket. Return a new socket object connected to the sam
 |      system resource. The new socket is non-inheritable.
 |
 |  get_inheritable(self)
 |      Get the inheritable flag of the socket
 |
 |  makefile(self, mode='r', buffering=None, *, encoding=None, errors=None, n
ine=None)
 |      makefile(...) -> an I/O stream connected to the socket
 |
 |      The arguments are as for io.open() after the filename,
 |      except the only mode characters supported are 'r', 'w' and 'b'.
 |      The semantics are similar too.  (XXX refactor to share code?)
 |
 |  set_inheritable(self, inheritable)
 |      Set the inheritable flag of the socket
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
 |
 |  family
 |      Read-only access to the address family for this socket.
 |
 |  type
 |      Read-only access to the socket type.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from _socket.socket:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signatur
 |
 |  bind(...)
 |      bind(address)
 |
 |      Bind the socket to a local address.  For IP sockets, the address is a
 |      pair (host, port); the host must refer to the local host. For raw pac
 |      sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
 |
 |  connect(...)
 |      connect(address)
 |
 |      Connect the socket to a remote address.  For IP sockets, the address
 |      is a pair (host, port).
 |
 |  connect_ex(...)
 |      connect_ex(address) -> errno
 |
 |      This is like connect(address), but returns an error code (the errno v
e)
 |      instead of raising an exception when an error occurs.
 |
 |  fileno(...)
 |      fileno() -> integer
 |
 |      Return the integer file descriptor of the socket.
 |
 |  getpeername(...)
 |      getpeername() -> address info
 |
 |      Return the address of the remote endpoint.  For IP sockets, the addre
 |      info is a pair (hostaddr, port).
 |
 |  getsockname(...)
 |      getsockname() -> address info
 |
 |      Return the address of the local endpoint.  For IP sockets, the addres
 |      info is a pair (hostaddr, port).
 |
 |  getsockopt(...)
 |      getsockopt(level, option[, buffersize]) -> value
 |
 |      Get a socket option.  See the Unix manual for level and option.
 |      If a nonzero buffersize argument is given, the return value is a
 |      string of that length; otherwise it is an integer.
 |
 |  gettimeout(...)
 |      gettimeout() -> timeout
 |
 |      Returns the timeout in seconds (float) associated with socket
 |      operations. A timeout of None indicates that timeouts on socket
 |      operations are disabled.
 |
 |  ioctl(...)
 |      ioctl(cmd, option) -> long
 |
 |      Control the socket with WSAIoctl syscall. Currently supported 'cmd' v
es are
 |      SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.
 |      SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval
 |
 |  listen(...)
 |      listen(backlog)
 |
 |      Enable a server to accept connections.  The backlog argument must be
 |      least 0 (if it is lower, it is set to 0); it specifies the number of
 |      unaccepted connections that the system will allow before refusing new
 |      connections.
 |
 |  recv(...)
 |      recv(buffersize[, flags]) -> data
 |
 |      Receive up to buffersize bytes from the socket.  For the optional fla
 |      argument, see the Unix manual.  When no data is available, block unti
 |      at least one byte is available or until the remote end is closed.  Wh
 |      the remote end is closed and all data is read, return the empty strin
 |
 |  recv_into(...)
 |      recv_into(buffer, [nbytes[, flags]]) -> nbytes_read
 |
 |      A version of recv() that stores its data into a buffer rather than cr
ing
 |      a new string.  Receive up to buffersize bytes from the socket.  If bu
rsize
 |      is not specified (or 0), receive up to the size available in the give
uffer.
 |
 |      See recv() for documentation about the flags.
 |
 |  recvfrom(...)
 |      recvfrom(buffersize[, flags]) -> (data, address info)
 |
 |      Like recv(buffersize, flags) but also return the sender's address inf
 |
 |  recvfrom_into(...)
 |      recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
 |
 |      Like recv_into(buffer[, nbytes[, flags]]) but also return the sender'
ddress info.
 |
 |  send(...)
 |      send(data[, flags]) -> count
 |
 |      Send a data string to the socket.  For the optional flags
 |      argument, see the Unix manual.  Return the number of bytes
 |      sent; this may be less than len(data) if the network is busy.
 |
 |  sendall(...)
 |      sendall(data[, flags])
 |
 |      Send a data string to the socket.  For the optional flags
 |      argument, see the Unix manual.  This calls send() repeatedly
 |      until all data is sent.  If an error occurs, it's impossible
 |      to tell how much data has been sent.
 |
 |  sendto(...)
 |      sendto(data[, flags], address) -> count
 |
 |      Like send(data, flags) but allows specifying the destination address.
 |      For IP sockets, the address is a pair (hostaddr, port).
 |
 |  setblocking(...)
 |      setblocking(flag)
 |
 |      Set the socket to blocking (flag is true) or non-blocking (false).
 |      setblocking(True) is equivalent to settimeout(None);
 |      setblocking(False) is equivalent to settimeout(0.0).
 |
 |  setsockopt(...)
 |      setsockopt(level, option, value)
 |
 |      Set a socket option.  See the Unix manual for level and option.
 |      The value argument can either be an integer or a string.
 |
 |  settimeout(...)
 |      settimeout(timeout)
 |
 |      Set a timeout on socket operations.  'timeout' can be a float,
 |      giving in seconds, or None.  Setting a timeout of None disables
 |      the timeout feature and is equivalent to setblocking(1).
 |      Setting a timeout of zero is the same as setblocking(0).
 |
 |  share(...)
 |      share(process_id) -> bytes
 |
 |      Share the socket with another process.  The target process id
 |      must be provided and the resulting bytes object passed to the target
 |      process.  There the shared socket can be instantiated by calling
 |      socket.fromshare().
 |
 |  shutdown(...)
 |      shutdown(flag)
 |
 |      Shut down the reading side of the socket (flag == SHUT_RD), the writi
side
 |      of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from _socket.socket:
 |
 |  proto
 |      the socket protocol
 |
 |  timeout
 |      the socket timeout


py2.x

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
 |
 |   [*] not available on all platforms!
 |
 |  Methods defined here:
 |
 |  __init__(self, family=2, type=1, proto=0, _sock=None)
 |
 |  accept(self)
 |      accept() -> (socket object, address info)
 |
 |      Wait for an incoming connection.  Return a new socket representing the
 |      connection, and the address of the client.  For IP sockets, the address
 |      info is a pair (hostaddr, port).
 |
 |  bind(...)
 |      bind(address)
 |
 |      Bind the socket to a local address.  For IP sockets, the address is a
 |      pair (host, port); the host must refer to the local host. For raw packe
 |      sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
 |
 |  close(self, _closedsocket=<class 'socket._closedsocket'>, _delegate_methods
('recv', 'recvfrom', 'recv_into', 'recvfrom_into', 'send', 'sendto'), setattr=<
uilt-in function setattr>)
 |      close()
 |
 |      Close the socket.  It cannot be used after this call.
 |
 |  connect(...)
 |      connect(address)
 |
 |      Connect the socket to a remote address.  For IP sockets, the address
 |      is a pair (host, port).
 |
 |  connect_ex(...)
 |      connect_ex(address) -> errno
 |
 |      This is like connect(address), but returns an error code (the errno val
e)
 |      instead of raising an exception when an error occurs.
 |
 |  dup(self)
 |      dup() -> socket object
 |
 |      Return a new socket object connected to the same system resource.
 |
 |  fileno(...)
 |      fileno() -> integer
 |
 |      Return the integer file descriptor of the socket.
 |
 |  getpeername(...)
 |      getpeername() -> address info
 |
 |      Return the address of the remote endpoint.  For IP sockets, the address
 |      info is a pair (hostaddr, port).
 |
 |  getsockname(...)
 |      getsockname() -> address info
 |
 |      Return the address of the local endpoint.  For IP sockets, the address
 |      info is a pair (hostaddr, port).
 |
 |  getsockopt(...)
 |      getsockopt(level, option[, buffersize]) -> value
 |
 |      Get a socket option.  See the Unix manual for level and option.
 |      If a nonzero buffersize argument is given, the return value is a
 |      string of that length; otherwise it is an integer.
 |
 |  gettimeout(...)
 |      gettimeout() -> timeout
 |
 |      Returns the timeout in seconds (float) associated with socket
 |      operations. A timeout of None indicates that timeouts on socket
 |      operations are disabled.
 |
 |  ioctl(...)
 |      ioctl(cmd, option) -> long
 |
 |      Control the socket with WSAIoctl syscall. Currently supported 'cmd' val
es are
 |      SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.
 |      SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).
 |
 |  listen(...)
 |      listen(backlog)
 |
 |      Enable a server to accept connections.  The backlog argument must be at
 |      least 0 (if it is lower, it is set to 0); it specifies the number of
 |      unaccepted connections that the system will allow before refusing new
 |      connections.
 |
 |  makefile(self, mode='r', bufsize=-1)
 |      makefile([mode[, bufsize]]) -> file object
 |
 |      Return a regular file object corresponding to the socket.  The mode
 |      and bufsize arguments are as for the built-in open() function.
 |
 |  sendall(...)
 |      sendall(data[, flags])
 |
 |      Send a data string to the socket.  For the optional flags
 |      argument, see the Unix manual.  This calls send() repeatedly
 |      until all data is sent.  If an error occurs, it's impossible
 |      to tell how much data has been sent.
 |
 |  setblocking(...)
 |      setblocking(flag)
 |
 |      Set the socket to blocking (flag is true) or non-blocking (false).
 |      setblocking(True) is equivalent to settimeout(None);
 |      setblocking(False) is equivalent to settimeout(0.0).
 |
 |  setsockopt(...)
 |      setsockopt(level, option, value)
 |
 |      Set a socket option.  See the Unix manual for level and option.
 |      The value argument can either be an integer or a string.
 |
 |  settimeout(...)
 |      settimeout(timeout)
 |
 |      Set a timeout on socket operations.  'timeout' can be a float,
 |      giving in seconds, or None.  Setting a timeout of None disables
 |      the timeout feature and is equivalent to setblocking(1).
 |      Setting a timeout of zero is the same as setblocking(0).
 |
 |  shutdown(...)
 |      shutdown(flag)
 |
 |      Shut down the reading side of the socket (flag == SHUT_RD), the writing
side
 |      of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
 |
 |  family
 |      the socket family
 |
 |  proto
 |      the socket protocol
 |
 |  recv
 |
 |  recv_into
 |
 |  recvfrom
 |
 |  recvfrom_into
 |
 |  send
 |
 |  sendto
 |
 |  type
 |      the socket type

妈蛋 要上课去了  待我上课的时候 仔细读读api    .想写个多人聊天工具/come  on!









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值