pythonsocket5
❶ python怎麼建立socket服務端
socket伺服器再細分可分為多種了,tcp,udp,websocket,都是調用socket模塊,但是具體實現起來有一點細微的差別
先給出一個tcp和udp通過socket協議實現的聊天室的例子
python聊天室(python2.7版本):
都是分別運行server.py和client.py,就可以進行通訊了。
TCP版本:
socket-tcp-server.py(服務端):
#-*-encoding:utf-8-*-
#socket.getaddrinfo(host,port,family=0,socktype=0,proto=0,flags=0)
#根據給定的參數host/port,相應的轉換成一個包含用於創建socket對象的五元組,
#參數host為域名,以字元串形式給出代表一個IPV4/IPV6地址或者None.
#參數port如果字元串形式就代表一個服務名,比如「http」"ftp""email"等,或者為數字,或者為None
#參數family為地主族,可以為AF_INET,AF_INET6,AF_UNIX.
#參數socktype可以為SOCK_STREAM(TCP)或者SOCK_DGRAM(UDP)
#參數proto通常為0可以直接忽略
#參數flags為AI_*的組合,比如AI_NUMERICHOST,它會影響函數的返回值
#附註:給參數host,port傳遞None時建立在C基礎,通過傳遞NULL。
#該函數返回一個五元組(family,socktype,proto,canonname,sockaddr),同時第五個參數sockaddr也是一個二元組(address,port)
#更多的方法及鏈接請訪問
#Echoserverprogram
fromsocketimport*
importsys
importthreading
fromtimeimportctime
fromtimeimportlocaltime
importtraceback
importtime
importsubprocess
reload(sys)
sys.setdefaultencoding("utf8")
HOST='127.0.0.1'
PORT=8555#設置偵聽埠
BUFSIZ=1024
classTcpServer():
def__init__(self):
self.ADDR=(HOST,PORT)
try:
self.sock=socket(AF_INET,SOCK_STREAM)
print'%disopen'%PORT
self.sock.bind(self.ADDR)
self.sock.listen(5)
#設置退出條件
self.STOP_CHAT=False
#所有監聽的客戶端
self.clients={}
self.thrs={}
self.stops=[]
exceptException,e:
print"%disdown"%PORT
returnFalse
defIsOpen(ip,port):
s=socket(AF_INET,SOCK_STREAM)
try:
s.connect((ip,int(port)))
#s.shutdown(2)
#利用shutdown()函數使socket雙向數據傳輸變為單向數據傳輸。shutdown()需要一個單獨的參數,
#該參數表示s了如何關閉socket。具體為:0表示禁止將來讀;1表示禁止將來寫;2表示禁止將來讀和寫。
print'%disopen'%port
returnTrue
except:
print'%disdown'%port
returnFalse
deflisten_client(self):
whilenotself.STOP_CHAT:
print(u'等待接入,偵聽埠:%d'%(PORT))
self.tcpClientSock,self.addr=self.sock.accept()
print(u'接受連接,客戶端地址:',self.addr)
address=self.addr
#將建立的clientsocket鏈接放到列表self.clients中
self.clients[address]=self.tcpClientSock
#分別將每個建立的鏈接放入進程中,接收且分發消息
self.thrs[address]=threading.Thread(target=self.readmsg,args=[address])
self.thrs[address].start()
time.sleep(0.5)defreadmsg(self,address):
#如果地址不存在,則返回False
ifaddressnotinself.clients:
returnFalse
#得到發送消息的clientsocket
client=self.clients[address]
whileTrue:
try:
#獲取到消息內容data
data=client.recv(BUFSIZ)
except:
print(e)
self.close_client(address)
break
ifnotdata:
break
#python3使用bytes,所以要進行編碼
#s='%s發送給我的信息是:[%s]%s'%(addr[0],ctime(),data.decode('utf8'))
#對日期進行一下格式化
ISOTIMEFORMAT='%Y-%m-%d%X'
stime=time.strftime(ISOTIMEFORMAT,localtime())
s=u'%s發送給我的信息是:%s'%(str(address),data.decode('utf8'))
#將獲得的消息分發給鏈接中的clientsocket
forkinself.clients:
self.clients[k].send(s.encode('utf8'))
self.clients[k].sendall('sendall:'+s.encode('utf8'))
printstr(k)
print([stime],':',data.decode('utf8'))
#如果輸入quit(忽略大小寫),則程序退出
STOP_CHAT=(data.decode('utf8').upper()=="QUIT")
ifSTOP_CHAT:
print"quit"
self.close_client(address)
print"alreadyquit"
break
defclose_client(self,address):
try:
client=self.clients.pop(address)
self.stops.append(address)
client.close()
forkinself.clients:
self.clients[k].send(str(address)+u"已經離開了")
except:
pass
print(str(address)+u'已經退出')
if__name__=='__main__':
tserver=TcpServer()
tserver.listen_client()
——————————華麗的分割線——————————
socket-tcp-client.py(客戶端):
#-*-encoding:utf-8-*-
fromsocketimport*
importsys
importthreading
importtime
reload(sys)
sys.setdefaultencoding("utf8")
#測試,連接本機
HOST='127.0.0.1'
#設置偵聽埠
PORT=8555
BUFSIZ=1024
classTcpClient:
ADDR=(HOST,PORT)
def__init__(self):
self.HOST=HOST
self.PORT=PORT
self.BUFSIZ=BUFSIZ
#創建socket連接
self.client=socket(AF_INET,SOCK_STREAM)
self.client.connect(self.ADDR)
#起一個線程,監聽接收的信息
self.trecv=threading.Thread(target=self.recvmsg)
self.trecv.start()
defsendmsg(self):
#循環發送聊天消息,如果socket連接存在則一直循環,發送quit時關閉鏈接
whileself.client.connect_ex(self.ADDR):
data=raw_input('>:')
ifnotdata:
break
self.client.send(data.encode('utf8'))
print(u'發送信息到%s:%s'%(self.HOST,data))
ifdata.upper()=="QUIT":
self.client.close()
printu"已關閉"
break
defrecvmsg(self):
#接收消息,如果鏈接一直存在,則持續監聽接收消息
try:
whileself.client.connect_ex(self.ADDR):
data=self.client.recv(self.BUFSIZ)
print(u'從%s收到信息:%s'%(self.HOST,data.decode('utf8')))
exceptException,e:
printstr(e)
if__name__=='__main__':
client=TcpClient()
client.sendmsg()
UDP版本:
socket-udp-server.py
#-*-coding:utf8-*-
importsys
importtime
importtraceback
importthreading
reload(sys)
sys.setdefaultencoding('utf-8')
importsocket
importtraceback
HOST="127.0.0.1"
PORT=9555
CHECK_PERIOD=20
CHECK_TIMEOUT=15
classUdpServer(object):
def__init__(self):
self.clients=[]
self.beats={}
self.ADDR=(HOST,PORT)
try:
self.sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.sock.bind(self.ADDR)#綁定同一個域名下的所有機器
self.beattrs=threading.Thread(target=self.checkheartbeat)
self.beattrs.start()
exceptException,e:
traceback.print_exc()
returnFalse
deflisten_client(self):
whileTrue:
time.sleep(0.5)
print"hohohohohoo"
try:
recvData,address=self.sock.recvfrom(2048)
ifnotrecvData:
self.close_client(address)
break
ifaddressinself.clients:
senddata=u"%s發送給我的信息是:%s"%(str(address),recvData.decode('utf8'))
ifrecvData.upper()=="QUIT":
self.close_client(address)
ifrecvData=="HEARTBEAT":
self.heartbeat(address)
continue
else:
self.clients.append(address)
senddata=u"%s發送給我的信息是:%s"%(str(address),u'進入了聊天室')
forcinself.clients:
try:
self.sock.sendto(senddata,c)
exceptException,e:
printstr(e)
self.close_client(c)
exceptException,e:
#traceback.print_exc()
printstr(e)
pass
defheartbeat(self,address):
self.beats[address]=time.time()
defcheckheartbeat(self):
whileTrue:
print"checkheartbeat"
printself.beats
try:
forcinself.clients:
printtime.time()
printself.beats[c]
ifself.beats[c]+CHECK_TIMEOUT<time.time():
printu"%s心跳超時,連接已經斷開"%str(c)
self.close_client(c)
else:
printu"checkp%s,沒有斷開"%str(c)
exceptException,e:
traceback.print_exc()
printstr(e)
pass
time.sleep(CHECK_PERIOD)
defclose_client(self,address):
try:
ifaddressinself.clients:
self.clients.remove(address)
ifself.beats.has_key(address):
delself.beats[address]
printself.clients
forcinself.clients:
self.sock.sendto(u'%s已經離開了'%str(address),c)
print(str(address)+u'已經退出')
exceptException,e:
printstr(e)
raise
if__name__=="__main__":
udpServer=UdpServer()
udpServer.listen_client()
——————————華麗的分割線——————————
socket-udp-client.py:
#-*-coding:utf8-*-
importsys
importthreading
importtime
reload(sys)
sys.setdefaultencoding('utf-8')
importsocket
HOST="127.0.0.1"
PORT=9555
#BEAT_PORT=43278
BEAT_PERIOD=5
classUdpClient(object):
def__init__(self):
self.clientsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.HOST=HOST
self.ADDR=(HOST,PORT)
self.clientsock.sendto(u'請求建立鏈接',self.ADDR)
self.recvtrs=threading.Thread(target=self.recvmsg)
self.recvtrs.start()
self.hearttrs=threading.Thread(target=self.heartbeat)
self.hearttrs.start()
defsendmsg(self):
whileTrue:
data=raw_input(">:")
ifnotdata:
break
self.clientsock.sendto(data.encode('utf-8'),self.ADDR)
ifdata.upper()=='QUIT':
self.clientsock.close()
break
defheartbeat(self):
whileTrue:
self.clientsock.sendto('HEARTBEAT',self.ADDR)
time.sleep(BEAT_PERIOD)
defrecvmsg(self):
whileTrue:
recvData,addr=self.clientsock.recvfrom(1024)
ifnotrecvData:
break
print(u'從%s收到信息:%s'%(self.HOST,recvData.decode('utf8')))if__name__=="__main__":
udpClient=UdpClient()
udpClient.sendmsg()
❷ 如何增加Python打開的socket數目
首先服務端這邊的實現如下:
import socket, traceback
host = '' # Bind to all interfaces
port = 51500
# Step1: 創建socket對象
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Step2: 設置socket選項(可選)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Step3: 綁定到某一個埠
s.bind((host, port))
# Step4: 監聽該埠上的連接
while 1:
try:
message, address = s.recvfrom(8192)
print "Got data from ", address
s.sendto("Data is received succeefully.", address)
except (KeyboardInterrupt, SystemExit):
print "raise"
raise
except :
print "traceback"
traceback.print_exc()
其中,host置為空,意思是可以綁定到所有的介面和地址,無論是哪個客戶端的請求,只要是綁定到了同樣的埠,那麼伺服器就可以監聽到這個請求。
在tcp連接中,監聽客戶端的請求需要用到listen或accept函數,並有一個專門的socket和遠程極其連接。
接著使我們的客戶端實現:
import socket, sys
# Step1: 輸入host和port信息
host = raw_input('please input host name: ')
textport = raw_input('please input textport: ')
# Step2: 創建socket對象
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
port = int(textport)
except ValueError:
port = socket.getservbyname(textport, 'udp')
# Step3: 打開socket連接
s.connect((host, port))
# Step4: 發送數據
print "Enter data to transmit: "
data = sys.stdin.readline().strip()
s.sendall(data)
# Step5: 接收伺服器發過來的數據
print "Looking for replies; press Ctrl-C or Ctrl-Break to stop"
while 1:
buf = s.recv(2048)
if not len(buf):
break
sys.stdout.write(buf)
這個例子就是這么簡單,實現起來和C語言版的差不多。看來,只要是了解socket編程的,用不同的語言實現也會相差無幾。
❸ python中使用socket編程,如何能夠通過UDP傳遞一個列表類型的數據
Python中的 list 或者 dict 都可以轉成JSON字元串來發送,接收後再轉回來。
首先
importjson
然後,把 list 或 dict 轉成 JSON
json_string=json.mps(list_or_dict)
如果你用的是Python3,這里的 json_string 會是 str 類型(即Python2的unicode類型),可能需要編碼一下:
if type(json_string) == six.text_type:
json_string = json_string.encode('UTF-8')
用socket發送過去,例如
s.sendto(json_string,address)
對方用socket接收,例如
json_string,addr=s.recvfrom(2048)
把JSON轉成 list 或 dict
list_or_dict=json.loads(json_string)
下面是個完整的例子:
client.py
#!/usr/bin/envpython
#-*-coding:UTF-8-*-
importsocket
importjson
importsix
address=('127.0.0.1',31500)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mylist=[1,2,3,4,5,6,7,8,9,10]
json_string=json.mps(mylist)
iftype(json_string)==six.text_type:
json_string=json_string.encode('UTF-8')
s.sendto(json_string,address)
s.close()
server.py
#!/usr/bin/envpython
#-*-coding:UTF-8-*-
importsocket
importjson
address=('127.0.0.1',31500)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(address)
json_string,addr=s.recvfrom(2048)
mylist=json.loads(json_string)
print(mylist)
s.close()
請先運行server.py,再運行client.py
❹ python的socket編程問題
struct在unpack的時候用大端方式讀取,先讀一個B,也就是一個位元組作為類型,然後讀一個H,也就是大端的兩位元組作為版本,然後是大段的兩位元組作為ln什麼的。
很多腳本語言都支持pack,unpack來序列化數據的,你要查一下具體的字元的含義。
❺ python怎樣建立socket伺服器
下面的例子是多線程實現的socket伺服器:
import socketimport threadingclass ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
# Set the response to echo back the recieved data
response = data
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return Falseif __name__ == "__main__":
while True:
port_num = input("Port? ")
try:
port_num = int(port_num)
break
except ValueError:
pass
ThreadedServer('',port_num).listen()
❻ python的socket的非阻塞實現
setblocking(0)之後就是非阻塞的。
select模塊只是說能夠同時處理多個socket,至於這些socket是阻塞還是非阻塞,都沒有關系。當然從性能上考慮,現在的趨勢是select+非阻塞。
❼ 請教一個關於python socket的問題
代碼如下:
Python code?#!/usr/bin/python from socket import socket, AF_INET, SOCK_STREAMfrom threading import Thread port = 50008host = 'localhost' def server(): sock = socket(AF_INET, SOCK_STREAM) sock.bind(('', port)) sock.listen(5) while True: conn, addr = sock.accept() data = conn.recv(1024) reply = 'server got: [%s]' % data conn.send(reply.encode()) def client(name): sock = socket(AF_INET, SOCK_STREAM) sock.connect((host, port)) sock.send(name.encode()) reply = sock.recv(1024) sock.close() print('client got: [%s]' % reply) if __name__ == '__main__': sthread = Thread(target=server) sthread.daemon = True sthread.start() for i in range(5): Thread(target=client, args=('client%s' % i,)).start()
在ubuntu下運行,報下面的異常信息:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.2/threading.py", line 740, in _bootstrap_inner
self.run()
File "/usr/lib/python3.2/threading.py", line 693, in run
self._target(*self._args, **self._kwargs)
File "./socket_test.py", line 21, in client
sock.connect((host, port))
socket.error: [Errno 111] Connection refused
把socket綁定的埠改為5000後,就沒有異常。
求指點!謝謝!
client got: [server got: [client1]]client got: [server got: [client0]]client got: [server got: [client2]]client got: [server got: [client3]]client got: [server got: [client4]]
我這正常的,你那是不是有兩個伺服器同時開了?把原來那個殺掉。
是因為埠被佔用了嗎?
❽ python-Socket服務端無限循環接受客戶端,但客戶端一直處於接受服務端信息狀態,無實際信息返回
第一個循環錯了。把第二個循環放在第一個循環裡面。accept完了就收發數據,循環收發。收發完了,關閉了,就回到accept的等待狀態 。
按你現在的邏輯是,accept完成後就一直等待,直到第二次accept
慢慢試驗。建議你accept完成後建立一個線程,單獨進行收發。
❾ 請教一個關於python socket的問題
代碼如下:
Python code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python
from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread
port = 50008
host = 'localhost'
def server():
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(('', port))
sock.listen(5)
while True:
conn, addr = sock.accept()
data = conn.recv(1024)
reply = 'server got: [%s]' % data
conn.send(reply.encode())
def client(name):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send(name.encode())
reply = sock.recv(1024)
sock.close()
print('client got: [%s]' % reply)
if __name__ == '__main__':
sthread = Thread(target=server)
sthread.daemon = True
sthread.start()
for i in range(5):
Thread(target=client, args=('client%s' % i,)).start()
在ubuntu下運行,報下面的異常信息:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.2/threading.py", line 740, in _bootstrap_inner
self.run()
File "/usr/lib/python3.2/threading.py", line 693, in run
self._target(*self._args, **self._kwargs)
File "./socket_test.py", line 21, in client
sock.connect((host, port))
socket.error: [Errno 111] Connection refused
把socket綁定的埠改為5000後,就沒有異常。
client got: [server got: [client1]]
client got: [server got: [client0]]
client got: [server got: [client2]]
client got: [server got: [client3]]
client got: [server got: [client4]]
我這正常的,你那是不是有兩個伺服器同時開了?把原來那個殺掉。