创建TCP服务器伪代码:
s = socket() #创建服务器套接字
s.bind() #套接字与地址绑定
s.listen() #监听连接
inf_loop: #服务器无限循环
cs = s.accept() #接受客户端连接,如果没有连接,则阻塞
comm_loop: #通信循环
cs.recv() / cs.send() #会话
cs.close() #关闭客户端套接字
s.close() #关闭服务器套接字
以下是代码:
#!/usr/bin/env python3 # encoding: utf-8 from socket import * from time import ctime HOST = '' PORT = 21567 BUFSIZE = 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 = tcpSerSock.recv(BUFSIZE) if not data: break tcpSerSock.send('[%s] %s' % (bytes(ctime(), 'uft-8'), data)) tcpSerSock.close() tcpSerSock.close()
相应地创建TCP客户端伪代码:
cs = socket()
cs.connect()
comm_loop: #通信循环
cs.recv() / cs.send() #会话
cs.close() #关闭客户端套接字
以下是实现代码:
#!/usr/bin/env python
# encoding: utf-8
from socket import *
HOST = '192.168.184.130'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('>')
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
print(data)
tcpCliSock.close()
在这个最简单的服务器套接字程序基础上,可以充分地扩充。