加载中…
个人资料
麦兜搞IT
麦兜搞IT
  • 博客等级:
  • 博客积分:0
  • 博客访问:1,585,148
  • 关注人气:537
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
相关博文
推荐博文
谁看过这篇博文
加载中…
正文 字体大小:

python学习笔记——socket网络编程(2)

(2009-08-25 16:00:00)
标签:

python

socket

网络编程

套接字

tcp

udp

杂谈

分类: Python

   首先总结一下一般的TCP和UDP连接服务器和客户端的内容和步骤。

TCP服务器端:

   1 创建套接字,绑定套接字到当地地址,然后开始监听连接。就是socket,bind,listen。

   2 进入循环,不断接受客户端的连接请求,然后接收传来的数据,当然也可以发送给对方数据。就是accept一个连接,然后recv数据。

   3 接收完毕可以关闭套接字,close。

    这个过程的伪代码如下:

ss=socket()    #创建服务器套接字

ss.bind()       #把本地地址绑到套接字上

ss.listen()      #监听连接

inf_loop:       #服务器无限循环

cs=ss.accept()   #接受客户端的连接

comm._loop:     #通信循环

cs.recv()/cs.send()  #对话

cs.close()         #关闭客户套接字

ss.close()         #关闭服务器套接字

 

TCP客户端:

   1 创建套接字,然后连接远端地址,socket ,connect。

   2 建立连接之后开始发送数据。Send(data),当然可以从缓冲区读取服务器发来的数据。Recv(BUFF)

   3 完毕后,关闭套接字。Close

   伪代码如下:

cs=socket()       #创建客户套接字

cs.connect()       #尝试连接服务器

comm._loop:     #通信循环

cs.send()/cs.recv()  #对话

cs.close()          #关闭套接字

 

UDP服务器端:
   1 创建套接字,并绑定到当地地址 socket,bing

   2 直接接收数据从buffer。Recvfrom(),这个函数接受到数据,和sender的地址(主机号,端口号),当然也可以发送数据到客户端,用sendto(data,addr)

   3 关闭套接字 close()

   伪代码:

Ss=socket()    #创建套接字

ss.bind()      #绑定

inf_loop:      #无限循环

ss.recvfrom()/sendto()  #对话

ss.close()      #关闭套接字

 

UDP客户端:

   1 创建套接字,socket

   2 进入循环,发送接收数据 sendto ,recvfrom

   3 关闭套接字 close()

   伪代码:

Cs=socket()   #创建

Comm_loop:   #循环接收发送

Cs.sendto()/recvfrom() #对话

Cs.close()     #关闭

 

 

Send() sendto() recv()recvfrom()

    我们发现在TCP连接中我们发生接收数据都是用的send()和recv()方法,而在UDP中用的sendto()和recvfrom()。这两对方法实现的作用差不多,但是参数有所不同,

    TCP中,send(data)和recv(buffer),因为在TCP中,传输数据之前连接已经建立,也就是说我们知道给谁发,或者收谁的数据。而在UDP中用,recvfrom(buffer)和sendto(data,addr),recvfrom可以接受到sender的addr,然后发送时,根据addr发送。因为UDP不是面向连接的,所以我们必须知道这个数据要发给谁,它的地址什么。

 

 

   附:看一下socket的help信息。有利于我们更好理解它的一些方法,这里只简单说就几个,更多的请看help文档。

先看一下socket对象的一些方法(method)

1 accept()接受一个连接,返回一个新的套接字(代表此连接)和客户端地址,是用在服务器端得,比如:

TcpCliSock,addr=TcpSerSock.accept()

只要客户端发来数据,这个就会运行,当然会考虑当前可接受的连接数目限制,这个由listen给出。

2 bind(addr) 绑定套接字到当地地址,对于IPsocket来说这个地址是用元组表示的一对主机号和端口号(host,port)。

比如:

ADDR=(host,port)

TcpSerSock.bind(ADDR)

3 connect(addr) 绑定套接字到远端的地址,当然这个地址和bind的参数一样的格式。

4 listen(n) 开始监听将要到的连接信息。n代表最多同时监听几路连接。

5 close( ) 关闭套接字

6 recv(buffer)接收数据 参数为一个buffer,先把接收数据放到buffer中,然后读取

Data=TcpCliSock.recv(BUFF)

    7 send(data), 发送数据,data为数据

8 recvfrom(buffer),也是从buffer中读取,但是返回的接受的数据,和发生者的地址

data,ADDR = udpCliSock.recvfrom(BUFSIZ)

9 sendto(data[, flags], addr),发送data到addr地址。

 

下面是help(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

 

   [*] 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(self, *args)

      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 packet

      sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])

 

  close(self)

      close()

     

      Close the socket.  It cannot be used after this call.

 

  connect(self, *args)

      connect(address)

     

      Connect the socket to a remote address.  For IP sockets, the address

      is a pair (host, port).

 

  connect_ex(self, *args)

      connect_ex(address) -> errno

     

      This is like connect(address), but returns an error code (the errno value)

      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(self, *args)

      fileno() -> integer

      

      Return the integer file descriptor of the socket.

 

  getpeername(self, *args)

      getpeername() -> address info

     

      Return the address of the remote endpoint.  For IP sockets, the address

      info is a pair (hostaddr, port).

 

  getsockname(self, *args)

      getsockname() -> address info

     

      Return the address of the local endpoint.  For IP sockets, the address

      info is a pair (hostaddr, port).

 

  getsockopt(self, *args)

      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(self, *args)

      gettimeout() -> timeout

     

      Returns the timeout in floating seconds associated with socket

      operations. A timeout of None indicates that timeouts on socket

      operations are disabled.

 |  

  ioctl(self, *args)

      ioctl(cmd, option) -> long

     

      Control the socket with WSAIoctl syscall. Currently only socket.SIO_RCVALL

      is supported as control. Options must be one of the socket.RCVALL_*

      constants.

 

  listen(self, *args)

      listen(backlog)

     

      Enable a server to accept connections.  The backlog argument must be at

      least 1; it specifies the number of unaccepted connection 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(self, *args)

      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(self, *args)

      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(self, *args)

      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(self, *args)

      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(self, *args)

      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

0

阅读 评论 收藏 转载 喜欢 打印举报/Report
  • 评论加载中,请稍候...
发评论

    发评论

    以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

      

    新浪BLOG意见反馈留言板 电话:4000520066 提示音后按1键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有