python 學習筆記_2 模擬socket程式設計 服務端、客戶端通訊(參考核心程式設計2程式碼實現)
伺服器端程式碼實現:
#!/usr/bin/env python
#coding=gbk
'''
接收客戶端字串,在欄位串前面打上當前時間,然後返回
server端採用 python2 linux下除錯執行
客戶端採用python3 windows下除錯執行(注意編碼格式)
'''
from socket import *
from time import ctime
buf=1024
sock_serv=socket(AF_INET,SOCK_STREAM)
sock_serv.bind(('103.20.2221.183',1234))
sock_serv.listen(5)
while 1:
print('server is listening..')
sock_client,addr=sock_serv.accept()
print('connect from:',addr)
while 1:
data=sock_client.recv(buf)
if not data:
break
sock_client.send('%s %s'%(ctime(),data))
sock_client.close()
sock_serv.close()
客戶端程式碼實現:
#coding=gbk
from socket import *
from time import ctime
buf=1024
sock_client=socket(AF_INET,SOCK_STREAM)
sock_client.connect(('103.20.2221.183',1234))
while 1:
data=input('please input something:')
if not data:
break
sock_client.send(data.encode('gbk'))
data=sock_client.recv(buf)
print('receive success:%s'%data.decode('gbk'))
sock_client.close()