TCP客户端持续交互与TCP服务端持续交互

TCP客户端持续交互

(ps:仅有代码,小伙伴们利用百度,冲啊!!!)

#coding=utf-8
from socket import *

client_socket = socket(AF_INET,SOCK_STREAM)
client_socket.connect(("127.0.0.1",6969))
while True:
    #给服务端发消息
    msg = input(">")
    client_socket.send(msg.encode("gbk"))
    if msg =="end":
        break
    #接收服务器端数据
    recv_data = client_socket.recv(1024) #最大接收1024字节
    print(f"服务器端说:{recv_data.decode('gbk')}")

client_socket.close()

TCP服务端持续交互

(ps:仅有代码,小伙伴们利用百度,冲啊!!!)

#coding=utf-8
from socket import *

server_socket = socket(AF_INET,SOCK_STREAM) #建立TCP套接字
server_socket.bind(("127.0.0.1",6969))  #本机监听8899端口
server_socket.listen(5)
print("等待接收连接!")
client_socket,client_info = server_socket.accept()
print("一个客户端建立连接成功!")
while True:
    recv_data = client_socket.recv(1024)  #最大接收1024字节
    recv_content = recv_data.decode('gbk')
    print(f"客户端说:{recv_content},来自:{client_info}")
    if recv_content == "end":
        break
    msg = input(">")
    client_socket.send(msg.encode("gbk"))

client_socket.close()
server_socket.close()

PS:127.0.0.1是本机ip,两个程序同时运行可持续交互数据。
PS:这个不完善,还需改进。

你可能感兴趣的:(网络编程萌新级,tcp/ip,网络,python)