python網路程式設計(TCP客戶端/伺服器端實現)
阿新 • • 發佈:2018-12-24
下面的程式實現的功能:客戶端發來訊息,伺服器端加上時間戳返回給使用者
伺服器端:
from socket import *
from time import ctime
import os
print(os.getpid())
HOST=''
POST=21567
BUFSIZ=1024
ADDR=(HOST,POST)#這裡是配置套接字,比C語言的簡單多了,沒那麼多結構體
tcpServerSocket=socket(AF_INET,SOCK_STREAM)#建立服務端的套接字
tcpServerSocket.bind(ADDR)#將地址與套接字繫結
tcpServerSocket.listen(5 )#然後就是監聽
try:
while True:
tcpClientSocket,clientaddr=tcpServerSocket.accept()#返回結果
print('...connected from :',clientaddr)
while True:
data=tcpClientSocket.recv(BUFSIZ).decode()
if not data:
break
tcpClientSocket.send(('[%s] %s' % (ctime(),data)).encode())
print(data)
else:
tcpClientSocket.close()
except Exception as e:
print(e)
finally:
tcpServerSocket.close()
客戶端:
__author__ = 'qingjin'
from socket import *
HOST='172.18.255.236'
POST=21567
BUFSIZE=1024
ADDR=(HOST,POST)
tcpClientSocket =socket(AF_INET,SOCK_STREAM)
tcpClientSocket.connect(ADDR)
while True:
data=input('>')
if data.lower()=='q':
break
tcpClientSocket.send(data.encode())
data=tcpClientSocket.recv(BUFSIZE).decode()
if not data:
break
print(data)
tcpClientSocket.close()
在這裡遇到了幾個問題,說明一下,對以後也有幫助:
1.socket.gaierror: [Errno 11001] getaddrinfo failed
這個其實就是主機地址格式不對
2.TypeError: ‘str’ does not support the buffer interface
這個就是要加上encode(string轉化成byte)和decode(相反)的原因
解決方法轉自:Python 3中套接字程式設計中遇到TypeError: ‘str’ does not support the buffer interface的解決辦法
3.我本來想通過建立執行緒來處理客戶端的請求,發現os.fork()不能用,這個是在unix下用的,windows下沒有。