在django项目中再开启一个socket服务
1.任意项目任意地方写一个createSocket.py文件(文件名任意)
import socket
from django.conf import settings
sock = socket.socket()
def startSocket():
ip = settings.LOCALHOSTIP
port = settings.LOCALHOSTPORT
sock.bind((ip, port))
sock.listen(10)
while True:
try:
conn, ip = sock.accept()
res = conn.recv(1024)
print(res)
except:
continue
2.在manage.py中开启进程,运行socket
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from multiprocessing import Process
from smartlabdemo.socketserver.createSocket import startSocket
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartlabdemo.settings.dev')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
# 开启进行监听硬件
'''
django项目中再开启一个socket会报错,原因是python一个进程下只能有一个socket服务
'''
socketProcess = Process(target=startSocket)
# 启动进程
socketProcess.start()
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
3.测试,写一个模拟客户端clientdemo.py
import socket
data = 'AA 55 00 00 00 90 00 01 00 00 00 00 00 01 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 2D 30 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 5F 4C 61 6D 70 73 68 61 64 65 5F 4C 32 35 34 00 00 00 00 72 65 70 6F 72 74 50 6F 77 65 72 44 61 74 61 00 00 00 00 00 00 00 00 3C 32 32 38 2E 30 33 56 00 00 00 30 2E 30 30 30 41 00 00 00 00 30 2E 30 30 57 00 00 00 00 00 30 2E 30 30 33 6B 57 2A 68 00 00 00 00 00 00 30 64 30 30 68 30 31 6D 35 36 73 00 00 00 00 38 0F '
client = socket.socket()
ip = '192.168.50.227'
port = 8100
client.connect((ip, port))
client.send(data.encode('utf8'))
print('发送成功')
4.结果
成功!!!!!!!!!!!!!
标签:00,socket,30,开启,django,2D,import From: https://www.cnblogs.com/chunyouqudongwuyuan/p/16888354.html