Python Socket實現簡單TCP Server/client功能樣本,pythonclient

來源:互聯網
上載者:User

Python Socket實現簡單TCP Server/client功能樣本,pythonclient

本文執行個體講述了Python Socket實現簡單TCP Server/client功能。分享給大家供大家參考,具體如下:

網路上關於socket的介紹文章數不勝數。自己記錄下學習的點點滴滴。以供將來複習學習使用。

socket中文的翻譯是通訊端,總感覺詞不達意。簡單的理解就是ip+port形成的一個嵌入式管理單元。也是程式中應用程式調用的介面。

在這裡我們先介紹如何啟動tcp 的server。

tcp串連中server部分,啟動一個ip和port口,在這個port口監聽,當收到client發來的請求,用一個新的連接埠port2同client建立串連。

socket啟動監聽的過程就是:

建立socket
bind連接埠
開始監聽
建立串連+繼續監聽

代碼:

'''This is a testing programthe program is used to start server'''import socketimport sysdef 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,為了程式的通用性,最好使用調用函數的方式擷取ip地址。

用到兩個函數socket.gethostname與socket.gethostbyname('name')

ip = socket.gethostbyname(socket.gethostname())

但是問題是一般情況下得到的ip地址為127.0.0.1。

對於使用配置或dhcp擷取的ip,可參考本站相關文章。

socket client 發起串連

流程為:

建立介面
發起串連
建立介面參數同socket server相同
發起串連的函數為socket.connect(ip,port)

這個地方的ip與port為socket server端的ip和監聽port。

程式碼範例:

# -*- coding: utf-8 -*-'''This is a testing programthe program is used to test socket client'''import socketimport sysdef 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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.