TCP通信
程序员文章站
2022-06-05 22:09:17
...
tcp服务器
# -*- coding:utf-8 -*-
import socket
def main():
# 创建套接字
service_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置属性,可以重复使用IP
service_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定地址
address = ("192.168.133.60", 10000)
service_socket.bind(address)
# 监听客户端
service_socket.listen(108)
while True:
new_socket, peer_ip = service_socket.accept()
while True:
recv_msg = new_socket.recv(1024)
print("from%s:%s" % (peer_ip, recv_msg.decode()))
# 发送消息
send_msg = input("<<")
new_socket.send(send_msg.encode())
if len(recv_msg) == 0:
print("客户端已经关闭")
break
if __name__ == "__main__":
main()
tcp客户端
# -*- coding:utf-8 -*-
import socket
def main():
cilent_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 去和服务器建立连接
address = ("192.168.133.60", 10000)
cilent_socket.connect(address)
# 发送消息
send_msg = input("<<")
cilent_socket.send(send_msg.encode())
if __name__ == "__main__":
main()
套接字服务器
# -*- coding:utf-8 -*-
import socket
def main():
# 创建套接字,用于监听连接
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置允许重用地址 socket层 重复使用(reuseaddr) 允许
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定地址
address = ("192.168.133.70", 10001)
listen_socket.bind(address)
# 设置成监听模式
listen_socket.listen(108) # 数字指这个服务器所能监听的对多的客户端长度
print("成功监听")
# 等待客户端连接
while True:
msg = listen_socket.accept()
print(msg)
print(123)
if __name__ == "__main__":
main()
上一篇: python语言实验 判断闰年
下一篇: 冀菜十大菜肴 个个来头不下,你都吃过吗