client:
import socket, sys
if __name__ == '__main__':
#處理引數
argv = sys.argv
if (len(argv)!=3) or (len(argv)==2 and argv[1]=='/?'):
print '>>>useage:', argv[0], ''
sys.exit(0)
host = argv[1] #server ip位址
port = int(argv[2]) #server 埠
print '>>>host:', host
print '>>>port:', port
#開啟socket
try:
sock = socket.socket(socket.af_inet, socket.sock_stream)
except socket.error:
print '>>>fail to open socket!'
sys.exit(1)
print '>>>socket opened...'
#連線try:
sock.connect((host, port))
except socket.error:
print '>>>fail to connect!'
sock.close()
print '>>>socket closed...'
sys.exit(1)
print '>>>socket connected...'
flag = 1 #迴圈標誌
ireturnvalue = 0 #系統返回值
#向server傳送資訊並回顯
while(flag):
msg = raw_input('>>>input message: ')
if msg == '':
continue
if msg == 'exit':
flag = 0
#傳送資訊
try:
sock.send(msg)
except socket.error:
print '>>>fail to send message!'
ireturnvalue = 1
break
print '>>>message sent :', msg
#接收資訊
try:
msg = sock.recv(1024)
except socket.error:
print '>>>fail to receive message!'
ireturnvalue = 1
break
print '>>>message received:', msg
#關閉socket,退出程式
sock.close()
print '>>>socket closed...'
print 'exit client program.'
sys.exit(ireturnvalue)
server:
try:
sock.bind((host, port))
except socket.error:
print 'fail to bind port!'
sock.close()
sys.exit(1)
print '>>>socket binding...'
try:
sock.listen(max_clients)
except socket.error:
print 'fail to listen!'
sock.close()
sys.exit(1)
print '>>>socket listening...'
threading.thread(target=listenthread, args=(sock,)).start()
python socket程式設計
python 編寫server的步驟 1.第一步是建立socket物件。呼叫socket建構函式。如 socket socket.socket family,type family引數代表位址家族,可為af inet或af unix。af inet家族包括internet位址,af unix家族用於...
python socket程式設計
客戶端 author lenovo fromsocketimport host localhost port 2157 bufsize 1024 addr host,port tcpclient socket af inet,sock stream tcpclient.connect addr wh...
Python Socket程式設計
在使用python做socket程式設計時,因為須要使用堵塞 預設 的方式來讀取資料流。此時對於資料的結束每次都須要自己處理。太麻煩。而且網上也沒找到太好的封裝。所以就自己寫了個簡單的封裝。封裝思路 1.客戶端每次請求均傳送乙個 socketrequest 物件,當中封裝詳細的資料。這裡使用json...