python利用socket模块,写一个最最简单的tcp通信

Posted on 2020-08-05 15:00  不叫柒桓叶  阅读(209)  评论(0编辑  收藏  举报

先说下我的参考资料哈:

https://www.cnblogs.com/liugp/p/10964981.html

https://blog.csdn.net/tonyrain123/article/details/81393129

 

正文开始哈:

服务器端代码:

# 再来简单的测试,这个是服务器端
import socket
import sys

BUF_SIZE = 1024
ip_port = (r"127.0.0.1", 11552)

my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 先拿到套接字,指定个ipv4以及流式数据包
my_socket.bind(ip_port) # 绑定
my_socket.listen(2)

# 循环等待客户端连接
while True:
print("waiting for client..")
conn, address = my_socket.accept()
print("connect from .." + str(address))

# 循环接受
while True:
ret = conn.recv(BUF_SIZE)
print("server receive data:" + str(ret))

if "END" in str(ret):
print("clent's gonna be offline.")
conn.send(bytes("BYE", encoding="utf-8"))
my_socket.close()
sys.exit()
else:
conn.send(bytes("server copy", encoding="utf-8"))



客户端代码:
# 这个是客户端
import socket

BUF_SIZE = 1024
ip_port = (r"127.0.0.1", 11552)

my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.connect(ip_port)

while True:
data = input(">>>")

my_socket.send(bytes(data, encoding="utf-8"))
recieve_data = my_socket.recv(BUF_SIZE)
print("client receive data = " + str(recieve_data))
if "BYE" in str(recieve_data):
print("server disconnect!")
break

我怎么运行的哈:
一个利用windows的cmd,直接输入命令:python server.py运行服务器
一个利用pycharm直接运行client.py

Copyright © 2024 不叫柒桓叶
Powered by .NET 9.0 on Kubernetes