day07_08 socket server
socket_server.py
__author__ = "Alex Li"
#-*-coding:utf-8-*-
#服务器端
#简单操作
# import socket
# server = socket.socket()
# server.bind(('localhost',6969)) #绑定要监听端口
# server.listen(5) #监听
# print("我要开始等电话了")
#
# server.accept() # 等电话打进来
# print("电话来了")
#
# data = server.recv(10240)
# print("recv:",data)
# server.send(data.upper()) #转换为大写
#
#
# server.close()
'''
#单次收发
import socket
server = socket.socket()
server.bind(('localhost',6969)) #绑定要监听端口
server.listen() #监听
print("我要开始等电话了")
conn, addr = server.accept() # 等电话打进来
# conn就是客户端连过来而在服务器端为其生成的一个连接实例
print(conn, addr)
print("电话来了")
data = conn.recv(1024)
print("recv:", data)
conn.send(data.upper())
server.close()
'''
import socket
server = socket.socket()
server.bind(('localhost',6969)) #绑定要监听端口
server.listen() #监听
print("我要开始等电话了")
while True:
conn, addr = server.accept() # 等电话打进来
# conn就是客户端连过来而在服务器端为其生成的一个连接实例
# print(conn, addr)
print("电话来了")
count = 0
while True:
data = conn.recv(1024)
print("recv:",data)
if not data:
print("client has lost...")
break
conn.send(data.upper())
count+=1
if count >10:break
server.close()
socket_client.py
__author__ = "Alex Li"
#客户端
# import socket
#
# client = socket.socket() #声明socket类型,同时生成socket连接对象
# client.connect(('localhost',6969))
#
# client.send(b"Hello World")
# data = client.recv(1024)
# print("recv:",data)
#
# client.close()
import socket
client = socket.socket() #声明socket类型,同时生成socket连接对象
client.connect(('localhost',9999))
'''
#单次收发
# client.send(b"Hello World")
client.send("我要下载a片".encode("utf-8"))
data = client.recv(1024)
print("recv:",data.decode())
'''
while True:
msg = input(">>:").strip()
if len(msg) == 0:continue
client.send(msg.encode("utf-8"))
data = client.recv(10240)
print("recv:",data.decode())
client.close()