先说下我的参考资料哈:
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