Python Socket實現(xiàn)簡單TCP Server/client功能示例
本文實例講述了Python Socket實現(xiàn)簡單TCP Server/client功能。分享給大家供大家參考,具體如下:
網(wǎng)絡上關于socket的介紹文章數(shù)不勝數(shù)。自己記錄下學習的點點滴滴。以供將來復習學習使用。
socket中文的翻譯是套接字,總感覺詞不達意。簡單的理解就是ip+port形成的一個管理單元。也是程序中應用程序調用的接口。
在這里我們先介紹如何啟動tcp 的server。
tcp連接中server部分,啟動一個ip和port口,在這個port口監(jiān)聽,當收到client發(fā)來的請求,用一個新的端口port2同client建立連接。
socket啟動監(jiān)聽的過程就是:
創(chuàng)建socket
bind端口
開始監(jiān)聽
建立連接+繼續(xù)監(jiān)聽
代碼:
'''
This is a testing program
the program is used to start server
'''
import socket
import sys
def start_tcp_server(ip, port):
#create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (ip, port)
#bind port
print 'starting listen on ip %s, port %s'%server_address
sock.bind(server_address)
#starting listening, allow only one connection
try:
sock.listen(1)
except socket.error, e:
print "fail to listen on port %s"%e
sys.exit(1)
while True:
print "waiting for connection"
client,addr = sock.accept()
print 'having a connection'
client.close()
if __name__ == '__main__':
start_tcp_server('10.20.0.20', 12345)
在這里有一個常用技巧,在start_tcp_server中,我們最常用到的是本機的ip,為了程序的通用性,最好使用調用函數(shù)的方式獲取ip地址。
用到兩個函數(shù)socket.gethostname與socket.gethostbyname('name')
ip = socket.gethostbyname(socket.gethostname())
但是問題是一般情況下得到的ip地址為127.0.0.1。
對于使用配置或dhcp獲取的ip,可參考本站相關文章。
socket client 發(fā)起連接
流程為:
創(chuàng)建接口
發(fā)起連接
創(chuàng)建接口參數(shù)同socket server相同
發(fā)起連接的函數(shù)為socket.connect(ip,port)
這個地方的ip與port為socket server端的ip和監(jiān)聽port。
代碼示例:
# -*- coding: utf-8 -*-
'''
This is a testing program
the program is used to test socket client
'''
import socket
import sys
def start_tcp_client(ip, port):
#server port and ip
server_ip = ip
servr_port = port
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tcp_client.connect((server_ip, server_port))
except socket.error:
print 'fail to setup socket connection'
tcp_client.close()
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python利用zhdate模塊實現(xiàn)農歷日期處理
zhdate模塊統(tǒng)計從1900年到2100年的農歷月份數(shù)據(jù)代碼,支持農歷和公歷之間的轉化,并且支持日期差額運算。本文將利用這一模塊實現(xiàn)農歷日期的處理,需要的可以參考一下2022-03-03
Python中optionParser模塊的使用方法實例教程
這篇文章主要介紹了Python中optionParser模塊的使用方法,功能非常強大,需要的朋友可以參考下2014-08-08
python實現(xiàn)MySQL指定表增量同步數(shù)據(jù)到clickhouse的腳本
這篇文章主要介紹了python實現(xiàn)MySQL指定表增量同步數(shù)據(jù)到clickhouse的腳本,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
Python代碼實現(xiàn)http/https代理服務器的腳本
這篇文章主要介紹了Python代碼做出http/https代理服務器,啟動即可做http https透明代理使用,通過幾百行代碼做出http/https代理服務器代碼片段,需要的朋友可以參考下2019-08-08

