05_tcp_Server

# Author:GuoZiLian
import socket


def main():
# 1. socket创建一个socket
tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# 2. bind绑定ip和port
tcp_server_socket.bind(("",7892))

# 3. listen监听
tcp_server_socket.listen(128) # 监听socket负责等待有新的客户端进行连接

while True:
# 4. accept等待客户端的链接
new_client_socket,client_addr = tcp_server_socket.accept() # 返回一个元组 | accept产生的新的socket用来为客户端服务
print(client_addr)

while True:
# 接收客户端发送过来的请求
recv_data = new_client_socket.recv(1024)
if recv_data:
print(recv_data.decode("gbk"))
# 回送一部分数据给客户端
new_client_socket.send("hahah-----OK----".encode("utf-8"))
else:
break

# 关闭两个socket
new_client_socket.close()
tcp_server_socket.close()


if __name__ == "__main__":
main()

posted @ 2019-04-02 14:42  比岸  阅读(154)  评论(0编辑  收藏  举报