Python 的socke編程示例
最近了解python的socket編程,寫了個小的例子
客戶端代碼:
#!/usr/bin/env python-- coding:utf-8 --
import socket import logging
def client_connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.connect(('127.0.0.1', 8080)) import time
time.sleep(2) s.send("1") print '1::', s.recv(1024) s.close()
if name == 'main': client_connect()</pre>
服務器端代碼:
#!/usr/bin/env python-- coding:utf-8 --
import socket import logging
def listen(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 8080)) s.listen(5) while True: connection, address = s.accept() print 'connection:::', connection print 'address:::', address
try: connection.settimeout(5) buf = connection.recv(1024) print 'buf::', buf if buf == '1': connection.send("welcome to server!") else: connection.send("please go out.") except socket.timeout: print 'time out' connection.close()
if name == 'main': print 'begin...' listen() print 'end...'</pre>
本文由用戶 aiguang 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!