python gui界面 tcp_通过python实现TCP编程
偽代碼:
ss = socket() #創(chuàng)建服務(wù)器套接字
ss.bind() #把地址綁定到套接字上
ss.listen() #監(jiān)聽(tīng)連接(最大連接數(shù))
info_loop: #服務(wù)器無(wú)限循環(huán)
cs = ss.accept() #接受客戶(hù)端連接
comm_loop: #通信循環(huán)
cs.recv()/cs.send() #對(duì)話(接收/發(fā)送)
cs.close() #關(guān)閉客戶(hù)端套接字
ss.close() #關(guān)閉服務(wù)器
所有的套接字都用socket.socket()函數(shù)來(lái)創(chuàng)建,服務(wù)器需要“坐在某個(gè)端口上“等待請(qǐng)求”所以它們必須要“綁定”到一個(gè)本地地址上,
由于TCP是一個(gè)面向連接的通信系統(tǒng),在TCP服務(wù)器開(kāi)始工作之前,要先完成一些設(shè)置,TCP服務(wù)器必須“監(jiān)聽(tīng)”連接,設(shè)置完成之后服務(wù)器
就可以進(jìn)入無(wú)限循環(huán)了。
一個(gè)簡(jiǎn)單的“單線程”服務(wù)器會(huì)調(diào)用accept()函數(shù)等待連接的到來(lái),默認(rèn)情況下accept()函數(shù)是阻塞的,即程序在連接到來(lái)之前會(huì)處于掛起狀態(tài),
套接字也支持非阻塞模式。
一旦接收到一個(gè)連接,accept()函數(shù)就會(huì)返回一個(gè)單獨(dú)的客戶(hù)端套接字用于后續(xù)的通信。
簡(jiǎn)單的TCP服務(wù)器
代碼如下
#!/usr/bin/env python3#-*- coding:utf-8 -*-
from socket import *
from time importctime
host= ''port= 12345buffsize= 2048ADDR=(host,port)
tctime=socket(AF_INET,SOCK_STREAM)
tctime.bind(ADDR)
tctime.listen(3)whileTrue:print('Wait for connection ...')
tctimeClient,addr=tctime.accept()print("Connection from :",addr)whileTrue:
data=tctimeClient.recv(buffsize).decode()if notdata:breaktctimeClient.send(('[%s] %s' %(ctime(),data)).encode())
tctimeClient.close()
tctimeClient.close()
TCP客戶(hù)端代碼:
#!/usr/bin/env python3#-*- coding:utf-8 -*-
from socket import *HOST='localhost'PORT= 12345BUFFSIZE=2048ADDR=(HOST,PORT)
tctimeClient=socket(AF_INET,SOCK_STREAM)
tctimeClient.connect(ADDR)whileTrue:
data= input(">")if notdata:breaktctimeClient.send(data.encode())
data=tctimeClient.recv(BUFFSIZE).decode()if notdata:break
print(data)
tctimeClient.close()
note:
如果實(shí)在ubuntu下面做練習(xí),需要在防火墻上添加allow條目,具體命令是
ufw allow 12345/tcp
也可以直接關(guān)閉防火:
ufw disable
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python gui界面 tcp_通过python实现TCP编程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【如何制作电子书】云展网教程 | 编辑纯
- 下一篇: 实例26:python