TCP服务器
如果需要创建一个TCP服务器的功能,需要的流程如下:
- socket创建一个套接字
- bind绑定ip和port
- listen使套接字变为可以被动连接
- accept等待客户端的链接
- 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(): tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local_addr = ("", 9999) tcp_server_socket.bind(local_addr) tcp_server_socket.listen(128) print("等待客户端的接入...") new_client_socket, client_addr = tcp_server_socket.accept() print("有新的客户端接入...") print("%s:%s已与服务器建立连接..." % (client_addr[0], client_addr[1])) 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()
|
210425142708
循环为多个客户端服务
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(): 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")) new_client_socket.close() print("为%s:%s服务完毕" % (client_addr[0], client_addr[1])) 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(): 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 new_client_socket.close() print("已经服务完成...") server_socket.close()
if __name__ == "__main__": main()
|