抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

TCP服务器

如果需要创建一个TCP服务器的功能,需要的流程如下:

  1. socket创建一个套接字
  2. bind绑定ip和port
  3. listen使套接字变为可以被动连接
  4. accept等待客户端的链接
  5. recv/send接收发送数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import socket


def main():
# 1. socket创建一个套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2. bind绑定ip和port
local_addr = ("", 9999)
tcp_server_socket.bind(local_addr)
# 3. listen使套接字变为可以被动连接
tcp_server_socket.listen(128)
# 4. accept等待客户端的链接
print("等待客户端的接入...")
new_client_socket, client_addr = tcp_server_socket.accept()
print("有新的客户端接入...")
print("%s:%s已与服务器建立连接..." % (client_addr[0], client_addr[1]))
# 5. recv/send接收发送数据
recv_data = new_client_socket.recv(1024)
print("%s" % recv_data.decode("gbk"))
# 回送数据
new_client_socket.send("ok".encode("gbk"))
# 关闭套接字
new_client_socket.close()
tcp_server_socket.close()


if __name__ == "__main__":
main()

20210425142708210425142708

循环为多个客户端服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import socket


def main():
# 创建socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定本地信息
server_socket.bind(("", 8888))
# 变主动为被动
server_socket.listen(128)
# 等待客户机的链接
while True:
print("等待客户端的链接...")
new_client_socket, client_addr = server_socket.accept()
print("%s:%s已经链接到服务器" % (client_addr[0], client_addr[1]))
# 接收数据
recv_data = new_client_socket.recv(1024)
# 打印接收到的数据
print(recv_data.decode("gbk"))
# 发送数据
new_client_socket.send("connect ok!".encode("gbk"))
# 关闭新socket
new_client_socket.close()
print("为%s:%s服务完毕" % (client_addr[0], client_addr[1]))
# 关闭socket
server_socket.close()


if __name__ == "__main__":
main()

循环为多个客户端服务(升级版)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import socket


def main():
# 创建socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定本地信息
server_socket.bind(("", 8888))
# 设置主动为被动
server_socket.listen(128)
# 监听
while True:
print("等待客户端的链接...")
new_client_socket, client_addr = server_socket.accept()
print("%s已经链接到服务器" % str(client_addr))
while True:
# 接收数据
recv_data = new_client_socket.recv(1024)
if recv_data:
# 打印接收到的数据
print(recv_data.decode("gbk"))
# 发送数据
new_client_socket.send("ok".encode("gbk"))
else:
break
# 关闭新链接的socket
new_client_socket.close()
print("已经服务完成...")
# 关闭socket
server_socket.close()



if __name__ == "__main__":
main()

评论