python 建立TCP伺服器 客戶端程式

2021-07-06 03:40:13 字數 2048 閱讀 6175



tcp伺服器程式(tstserv.py):

from socket import *

from time import ctime

host = ''

port = 21567

bufsiz = 1024

addr = (host, port)

tcpsersock = socket(af_inet, sock_stream)

tcpsersock.bind(addr)

tcpsersock.listen(5)

while true:

print 'waiting for connection...'

tcpclisock, addr = tcpsersock.accept()

print '...connected from:', addr

while true:

data = tcpclisock.recv(bufsiz)

if not data:

break

tcpclisock.send('[%s] %s' %(ctime(), data))

tcpclisock.close()

tcpsersock.close()

tcp客戶端程式(tstclnt.py):

from socket import *

host = 'localhost'

port = 21567

bufsiz = 1024

addr = (host, port)

tcpclisock = socket(af_inet, sock_stream)

tcpclisock.connect(addr)

while true:

data = raw_input('> ')

if not data:

break

tcpclisock.send(data)

data1 = tcpclisock.recv(bufsiz)

if not data1:

break

print data1

tcpclisock.close()

執行說明:先執行伺服器程式,作用類似於開啟伺服器保持等待客戶請求,再執行客戶端程式。

執行介面如下:

伺服器端:

d:\code\ex>python tstserv.py

waiting for connection...

...connected from: ('127.0.0.1', 2883)

waiting for connection...

...connected from: ('127.0.0.1', 2885)

waiting for connection...

...connected from: ('127.0.0.1', 2889)

waiting for connection...

...connected from: ('127.0.0.1', 2891)

waiting for connection...

...connected from: ('127.0.0.1', 2892)

waiting for connection...

...connected from: ('127.0.0.1', 2893)

waiting for connection...

客戶端:

d:\code\ex>python tstclnt.py

> 1

[thu feb 02 15:52:21 2012] 1

> 2

[thu feb 02 15:52:22 2012] 2

> 3

[thu feb 02 15:52:22 2012] 3

> 5

[thu feb 02 15:52:23 2012] 5

> 6

[thu feb 02 15:52:24 2012] 6

>

d:\code\ex>

參考《python核心程式設計》。

Python 建立TCP伺服器的方法

問題 你想實現乙個伺服器,通過tcp協議和客戶端通訊。解決方案 建立乙個tcp伺服器的乙個簡單方法是使用 socketserver 庫。例如,下面是乙個簡單的應答伺服器 from socketserver import baserequesthandler,tcpserver class echoh...

簡單TCP伺服器建立

簡單tcp伺服器建立 實現tcp伺服器的建立,實現迴圈與客戶端聊天,並且獲取客戶端資訊.tcp程式設計步驟 1 建立套接字socket 買手機.2 套接字繫結 bind 繫結手機卡.3 監聽套接字 listen 等待其他人打 4 接受客戶端請求 accept 接 進行資料的互動過程.通話內容.5 關...

swoole 建立tcp伺服器

server.php 建立tcp伺服器 date 2019 1 15 serv new swoole server 127.0.0.1 9501 監聽連線進入事件 serv on connect function serv,fd 監聽資料接收事件 serv on receive function s...