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
    分別對(duì)應(yīng)socket()函數(shù)的三個(gè)參數(shù).

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()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钓账,一起剝皮案震驚了整個(gè)濱河市黎做,隨后出現(xiàn)的幾起案子痹扇,更是在濱河造成了極大的恐慌材蹬,老刑警劉巖苫亦,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件详炬,死亡現(xiàn)場(chǎng)離奇詭異叹哭,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)咧党,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來陨亡,“玉大人傍衡,你說我怎么就攤上這事「喝洌” “怎么了蛙埂?”我有些...
    開封第一講書人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)遮糖。 經(jīng)常有香客問我绣的,道長(zhǎng),這世上最難降的妖魔是什么欲账? 我笑而不...
    開封第一講書人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任屡江,我火速辦了婚禮,結(jié)果婚禮上赛不,老公的妹妹穿的比我還像新娘惩嘉。我一直安慰自己,他們只是感情好踢故,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開白布文黎。 她就那樣靜靜地躺著,像睡著了一般殿较。 火紅的嫁衣襯著肌膚如雪耸峭。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,604評(píng)論 1 305
  • 那天斜脂,我揣著相機(jī)與錄音抓艳,去河邊找鬼。 笑死帚戳,一個(gè)胖子當(dāng)著我的面吹牛玷或,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播片任,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼偏友,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了对供?” 一聲冷哼從身側(cè)響起位他,我...
    開封第一講書人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤氛濒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后鹅髓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體舞竿,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年窿冯,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了骗奖。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡醒串,死狀恐怖执桌,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情芜赌,我是刑警寧澤仰挣,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站缠沈,受9級(jí)特大地震影響膘壶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜博烂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一香椎、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧禽篱,春花似錦畜伐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至悼吱,卻和暖如春慎框,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背后添。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來泰國打工笨枯, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人遇西。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓馅精,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親粱檀。 傳聞我的和親對(duì)象是個(gè)殘疾皇子洲敢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,509評(píng)論 0 23
  • 自上次去三皇子那又過去了幾天,綠綺已經(jīng)差不多摸清了這個(gè)公主原本的脾氣茄蚯,和關(guān)系好的人之間會(huì)丟掉禮儀压彭,但如果在一般人...
    東兔角閱讀 150評(píng)論 0 1
  • 獨(dú)倚闌干月無痕睦优,日西沉,黯銷魂壮不。 秋千閑掛汗盘,空憶笑聲頻。 切莫等閑扔紅豆忆畅,留贈(zèng)與衡未,意中人。 作于2015年3月3日晚
    霙愔閱讀 315評(píng)論 5 4
  • 我叫蘇利蕓家凯,來自廣西的山嘎啦里!因家庭條件不好如失,初中畢業(yè)后就跟著我姐南下打工了绊诲。在廠里上班,每天都是三點(diǎn)一線的生活...
    蕓寶兒閱讀 157評(píng)論 0 0
  • 王漢文 暑去冬來 你還在秋風(fēng)中等待 金桂早已成泥 菊花也已經(jīng)開敗 你是一朵奇葩 錯(cuò)過了春天 就不想再開 緊閉的花蕾...
    王漢文閱讀 603評(píng)論 5 4