tcp基础写法

This commit is contained in:
lsy2246 2024-04-02 00:38:08 +08:00
parent 0e3d300e96
commit cc38a382f0
2 changed files with 47 additions and 0 deletions

18
python/code/TCP/client.py Normal file
View File

@ -0,0 +1,18 @@
from socket import socket, AF_INET, SOCK_STREAM
client_socket = socket(AF_INET, SOCK_STREAM)
ip = "localhost"
port = 8778
client_socket.connect((ip, port))
info = ""
while info != "exit":
send_data = input("请输入:")
client_socket.send(send_data.encode("utf-8"))
if send_data == "exit":
break
info = client_socket.recv(1024).decode("utf-8")
print("收到服务端响应数据:", info)
client_socket.close()

29
python/code/TCP/server.py Normal file
View File

@ -0,0 +1,29 @@
from socket import socket, AF_INET, SOCK_STREAM
# AF_INET 使用Internet之间的进程进行通信
# SOCK_STRAEAM 表明使用TCP协议进行编程
# 1.创建socket对象
server_socket = socket(AF_INET, SOCK_STREAM)
# 2.绑定ip和端口
ip = "localhost"
port = 8778
server_socket.bind((ip, port))
# 使用listen()监听
server_socket.listen(5)
print("服务器已近启动")
client_socket, client_obj = server_socket.accept() # 系列解包赋值
# 等待客户端连接
info = ""
while info != "exit":
##接收数据
data = client_socket.recv(1024)
print("客户端发送过来的数据为:", data.decode("utf-8")) # 要求客服端发过来的是utf-8进行编码的
##返回数据
client_socket.send(data)
if data.decode("utf-8") == "exit":
break
# 关闭服务器
client_socket.close()