tcp循环发消息

时间:2022-12-15 14:13:33

  

 

服务端:(server1)

 

import socket
sk = socket.socket()
# 注册主机
sk.bind( ("127.0.0.1",9000) ) # 参数是元组
# 开启监听
sk.listen()
# 三次握手
# conn,addr = sk.accept()
 
'''
conn:
<socket.socket fd=480, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 9000), raddr=('127.0.0.1', 60879)>
addr:
('127.0.0.1', 60879)
'''
# print(conn,addr)
 
while True:
    conn,addr = sk.accept()
    while True:
        msg = conn.recv(1024)
        print(msg.decode("utf-8"))
        # 服务器发消息
        message = input("我要发的数据:>>>")
        conn.send(message.encode("utf-8"))
        if message == "q":
            break
 
# 四次挥手
conn.close()
# 退还端口
sk.close()

 

客户端:(client1)

import socket
sk = socket.socket()
sk.connect( ("127.0.0.1",9000) )
 
 
while True:
    message = input(">>>:")
    sk.send(message.encode("utf-8"))
    # 接收服务器发过的消息
    res = sk.recv(1024)
    if res == b"q":
        break
     
    print(res.decode("utf"))
sk.close()

 

 

服务端:(server2)

# 服务器
import socketserver
import socket
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        # 自定义的逻辑...
        print("----> 执行这句话")
        # print(self.request)
        # print(self.client_address)
        conn = self.request
        while True:
            # 接收消息
            msg = conn.recv(1024)
            print(msg.decode("utf-8"))
            # pass
             
            conn.send(b'world')
         
# 生成一个对象
# ThreadingTCPServer( "ip端口号" ,"自定义的类"  )
server = socketserver.ThreadingTCPServer( ("127.0.0.1",9000) , MyServer )
# 循环调用
server.serve_forever()
 
'''
try:
    # lst = [1, 2, 3]
    # print(lst[99])
    print(333)
finally:
    print(1)
    print(2)
'''
 
"""
try .. finally ..
不论try 代码块里面的代码是不是报错,
都会执行finally这个代码块中的内容.
作用:正常情况,如果报错,后面的代码一律不执行,
但是特殊条件下,又必须在报错的行为中,执行某些代码,
那么这样的代码加到finally当中
"""

 

客户端: client2

# 客户端
import socket
sk = socket.socket()
sk.connect( ("127.0.0.1",9000) )
 
while True:
    # 发消息
    sk.send(b"hello")
     
    # 接收服务器消息
    msg = sk.recv(1024)
    print(msg.decode("utf-8"))
 
 
sk.close()