To create a TCP server pseudo-code:
s = socket () #创建服务器套接字
S.bind () #套接字与地址绑定
S.listen () #监听连接
Inf_loop: #服务器无限循环
cs = s.accept () #接受客户端连接, if there is no connection, block
Comm_loop: #通信循环
CS.RECV ()/cs.send () #会话
Cs.close () #关闭客户端套接字
S.close () #关闭服务器套接字
Here's the code:
#!/usr/bin/env python3# encoding: utf-8from socket import *from time import ctimehost = ' port = 21567bufsize = 1024addr = (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 ()
Create the TCP client pseudo-code accordingly:
CS = socket ()
Cs.connect ()
Comm_loop: #通信循环
CS.RECV ()/cs.send () #会话
Cs.close () #关闭客户端套接字
Here is the implementation code:
#!/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 ()
On the basis of this simplest server socket program, it can be fully expanded.
Python core third edition of Network programming