Python 创建TCP/IP通信

服务器端:

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpServSock = socket(AF_INET, SOCK_STREAM)
tcpServSock.bind(ADDR)
tcpServSock.listen(5)

print('waiting for connection...')
tcpClientSock, addr = tcpServSock.accept()
print('...connected from: ', addr)

while True:
	data = str(tcpClientSock.recv(BUFSIZ), encoding='utf-8')
	if not data:
		break
	tcpClientSock.send(bytes('[%s]%s'%(ctime(), data), 'utf-8'))

tcpClientSock.close()
tcpServSock.close()

客户端:

from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpClientSock = socket(AF_INET, SOCK_STREAM)
tcpClientSock.connect(ADDR)

while True:
	data = input('> ')
	if not data:
		break
	tcpClientSock.send(bytes(data, 'utf-8'))
	data = tcpClientSock.recv(BUFSIZ)
	if not data:
		break
	print(str(data, encoding='utf-8'))

tcpClientSock.close()


你可能感兴趣的:(Python)