Posted on 2009-09-15 21:35
silentneil 閱讀(299)
評論(0) 編輯 收藏 引用 所屬分類:
Python
server.py
# -*- coding: cp936 -*-
import socket
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('192.168.1.106', 8001))
sock.listen(5) #最多允許5個客戶連接到服務(wù)器,值至少為1
while True:
# connection是一個新的socket對象,服務(wù)端通過它與客戶端通信
# address是客戶端的internet地址
connection, address = sock.accept() #等待(waiting)狀態(tài)
print 'connected from ', address
try:
connection.settimeout(5) #設(shè)置超時時間
# recv時為阻塞(blocked)狀態(tài)
buf = connection.recv(1024) #接收的最大數(shù)據(jù)量為1024,如果超過則被截短
if buf == '1':
connection.send('welcome to server!')
else:
connection.send('please go out!')
except socket.timeout:
print 'time out'
connection.close()
client.py
import socket, time
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.106', 8001))
time.sleep(2)
sock.send('1')
print sock.recv(1024)
sock.close