Python Socket 编程

参考

Socket family

  • AF_INET a pair(host,port) is used for the address family, where host is a string representing either a host name in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like'100.50.200.5', and port is an integer.

constants

  1. socket.AF_UNIX, socket.AF_INET, socket.AF_INET6
  2. socket.SOCK_STRESM, socket.SOCK_DGRAM, socket.SOCK_RAW, socket.SOCK_RDM, socket.SOCK_SEQPACKET
  3. socket.SOCK_CLOEXEC, socket.SOCK_NONBLOCK
    分别对应socket()函数的三个参数.

functions

socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
Create a new socket using the given address family, socket type and protocol number.

Socket object

socket.accept()
Accept a connection.The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

socket.bind(address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family).

socket.close()
Mark the socket closed.

socket.connect(address)
Connect to a remote socket at address. (The format of address depends on the address family).

socket.listen([backlog])
Enable a server to accept connections. If backlog is specified, it 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.

socket.recv(bufsize[, flags])
Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

Note For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

socket.send(bytes[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above.

TCP server

from time import sleep, ctime  
import socket  

HOST = ''
port = 12345
BUFSIZE = 1024
ADDR = (HOST, port)

tcpSerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print 'waiting for connection...'
    tcpCliSock, addr = tcpSerSock.accept()
    print '...connected from:', addr

    while True:
        data = tcpCliSock.recv(BUFSIZE)
        if not data:
            break
        tcpCliSock.send('[%s] %s' %(ctime(), data))
    
    tcpCliSock.close()

tcpSerSock.close()  

TCP client

import socket

HOST = 'localhost'
PORT = 21456
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = raw_input(">")
    if not data:
        break
    tcpCliSock.send(data)
    data = tcpCliSock.recv(BUFSIZE)
    if not data:
        break
    print data

tcpCliSock.close()

UDP server

from socket import *
from time import ctime

HOST = ''
PORT = 21456
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(ADDR)

while True:
    print 'waiting for message...'
    data, addr = udpSerSock.recvfrom(BUFSIZE)
    udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)
    print '...recerived from and returned to:', addr

udpSerSock.close()

UDP client

from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True:
    data = raw_input(">")
    if not data:
        break
    udpCliSock.sendto(data, ADDR)
    data, ADDR = udpCliSock.recvfrom(BUFSIZE)
    if not data:
        break
    print data

udpCliSock.close()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,917评论 0 23
  • 自上次去三皇子那又过去了几天,绿绮已经差不多摸清了这个公主原本的脾气,和关系好的人之间会丢掉礼仪,但如果在一般人...
    东兔角阅读 155评论 0 1
  • 独倚阑干月无痕,日西沉,黯销魂。 秋千闲挂,空忆笑声频。 切莫等闲扔红豆,留赠与,意中人。 作于2015年3月3日晚
    霙愔阅读 332评论 5 4
  • 我叫苏利芸,来自广西的山嘎啦里!因家庭条件不好,初中毕业后就跟着我姐南下打工了。在厂里上班,每天都是三点一线的生活...
    芸宝儿阅读 165评论 0 0
  • 王汉文 暑去冬来 你还在秋风中等待 金桂早已成泥 菊花也已经开败 你是一朵奇葩 错过了春天 就不想再开 紧闭的花蕾...
    王汉文阅读 615评论 5 4