一、创建套接字示例(服务端)
import socket #导入模块
import time #导入模块
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建TCP套接字
address = ('127.0.0.1', 8888)
s.bind(address) #为TCP套接字绑定IP及端口
s.listen(10) #启动TCP监听,同时接受10个socket连接。
print("start server!")
while 1:
try:
conn, addr = s.accept() #设置为:被动接收TCP客户端连接
if conn:
print("recv client from {0}".format(addr)) #打印接收到的客户端IP、端口
while 1:
data = conn.recv(2048) #指定连接最大接受的数据量为 2048
print("recv data: {0}".format(data.decode('utf-8'))) #打印接收到的数据
conn.sendall(data.decode('utf-8').upper().encode('utf-8')) #发送完整的TCP消息
else:
time.sleep(5) #暂定5秒
except Exception as e:
conn.close() #关闭连接
二、创建套接字示例(客户端)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('127.0.0.1', 8888)
s.connect(address)
flage = 1
print("start client!")
while flage:
word = input("word: ")
if word == "exit":
flage = 0
s.sendall(word.encode('utf-8'))
data = s.recv(2048)
print("RECV: {0}".format(data.decode('utf-8')))
s.close()