tcp客户端
import socket
def main():
#创建tcp套接字
socket_tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#连接字
sever_ip = input("请输入连接的IP:")
sever_port = int(input("请输入连接的端口号:"))
#绑定本地信息
socket_tcp.bind(("",7807))
socket_tcp.connect((sever_ip,sever_port))
while True:
while True:
#发送
send_date = input("请输入发送的数据:")
socket_tcp.send(send_date.encode("utf-8"))
if send_date == "exit":
break
#关闭套接字
while True:
#接收信息
recv_date = socket_tcp.recv(1024)
print("客户端回复的消息是:%s"%recv_date.decode("utf-8"))
break
ligen = input("是否继续(x/y):")
if ligen == "y":
socket_tcp.close()
break
if __name__ == "__main__":
main()
服务器端
import socket
def rece_mess(socket_tcp):
while True:
#等待(accept)
print("------正在接通客户------")
new_accer,add_accer = socket_tcp.accept()
print("------已连接到客户------")
print("%s以连通"%str(add_accer))
send_mess(new_accer)
#关闭套接字
new_accer.close()
print("服务结束")
def send_mess(new_accer):
while True:
#接收信息
recv_date = new_accer.recv(1024)
print("客户端回复的消息是:%s"%recv_date.decode("utf-8"))
if recv_date == "exit":
continue
if recv_date:
#给客户端回消息
send_data = input("你要发送的消息:")
new_accer.send(send_data.encode("utf-8"))
#new_accer.send("请继续输入".encode("utf-8"))
else:
break
def main():
#创建套接字
socket_tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定本地信息
socket_tcp.bind(("",8503))
#监听(listen)
socket_tcp.listen(128)
rece_mess(socket_tcp)
socket_tcp.close()
if __name__ == "__main__":
main()