4.3 TCP服务端搭建
TCP通信要明白的“三次握手”,“四次挥手”在前面章节以详细说明了,其实在实际的开发过程中,并不需要过多的去关注整个TCP通信建立的过程,你所使用的后端语言,都已经将通信的过程封装成一个个函数,只需要学会如何使用这些函数,去完成相应的功能即可。
基于python 语言的TCP服务器搭建,一般分为一下几个步骤:
1 2 3 4 5 6 7 8 9 10 11
|
tcp_server_socket.bind(address) tcp_server_socket.listen(128) client_socket,clientAddr=tcp_server_socket.accept() while True: recv_data = client_socket.recv(1024) print('接收到的数据为:', recv_data.decode('gbk')) client_socket.send("thank you !".encode('gbk'))
|
执行上述代码,可以创建个简单的TCP 服务端,但是该服务端是单线程的,也就是说这个服务端启动后,同一时间如若有多个客户端同时访问,只会一个一个进行处理,前面的没有释放连接,后面的连接就只能等待。这是很致命的,对于单线程的服务端,不及时释放,就会影响到其他客户端访问。所以,在实际应用中,TCP服务端都做的是多线程的,可以同时处理多个客户端的请求。
#####多线程TCP服务端设计:
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| from socket import * import json import threading from pymysql import * import datetime socket_serverlist=[]
def send_socket(client_socket): while True: data=input("PLEASE INPUTE") client_socket.send(data.encode('gbk'))
def recv_socket(client_socket,cs1,conn): while True: recv_data = client_socket.recv(1024) try: r_data = recv_data.decode('utf8') j_data = json.loads(r_data) except Exception as f: print(f) continue print('recv_data is:%s' % r_data) now_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') mac=j_data['addr'] name="mesh_"+mac[12:14]+mac[15:17] print("name is %s"%name) date=str(j_data['data']) sql='insert into device_history_data values ("0","'+name+'","'+mac+' ","'+date+' "," '+ now_time+'")' count = cs1.execute(sql) conn.commit() if recv_data: client_socket.send(r_data.encode('utf8')) print('send_data is: COMD ok') print(threading.active_count()) else: break client_socket.close() def creat_socket(tcp_server_socket,cs1,conn): while True: print("waite client onload") client_socket, clientAddr = tcp_server_socket.accept() print("client ID:%s" % str(clientAddr)) client_socket.settimeout(10) t = threading.Thread(target=recv_socket, args=(client_socket, cs1,conn)) socket_serverlist.append(t); t.start() print(socket_serverlist)
def main(): tcp_server_socket = socket(AF_INET, SOCK_STREAM) address = ('', 8000) tcp_server_socket.bind(address) conn = connect(host='192.168.1.128', port=3306, database= 'mesh_device _data', user='root', password='mysql', charset='utf8') cs1 = conn.cursor() tcp_server_socket.listen(128) creat_socket(tcp_server_socket,cs1,conn) if __name__ == '__main__': main()
|