歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python Socket編程實現的簡單tcp迭代服務器

Python Socket編程實現的簡單tcp迭代服務器

日期:2017/3/1 9:38:46   编辑:Linux編程

Python Socket編程實現的簡單tcp迭代服務器

與C/C++ Socket編程對比見 http://www.linuxidc.com/Linux/2014-10/107871.htm

服務器

import socket

PORT = 9999
BACKLOG = 5
MAXLINE = 1024

listenfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listenfd.bind(('',PORT))
listenfd.listen(BACKLOG)

while True:
connfd, connaddr = listenfd.accept()
print 'a new connection'
buf = []
buf = connfd.recv(MAXLINE)
print buf
connfd.send('Hello,this is server')
connfd.close()

客戶端:

import socket

addr = '127.0.0.1'
port = 9999
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockfd.connect((addr, port))
sockfd.send('Hello,this is client')
buf = []

while True:
recv_data = sockfd.recv(1024)
if recv_data:
buf.append(recv_data)
else:
break

data = ''.join(buf)
print data
sockfd.close()

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved