![](/img/trans.png)
[英]How to recieve data from a one socket and send it to another socket in python?
[英]one python script to open a socket, another to send data over the socket
我正在研究Asterisk AGI和Python 3的集成。 我在編寫腳本時遇到麻煩,我想這可能是因為它一次運行了太多,最后關閉了套接字導致了問題。
如果我一次打進來一個電話,或者他們錯開了,腳本將完美執行。 如果我有多個電話同時打來,請說5(在這種情況下很常見),接收數據的套接字只能處理2個完全完成的腳本。
我試圖最小化腳本,以查看是否可以使它更快地執行,除去不需要的內容,刪除日志記錄,刪除#out行。 我唯一能做的就是嘗試錯開通話,這不是一個可行的選擇。
#!/usr/bin/env python3
import serial
import re
from time import sleep
import logging
import logging.handlers
from configparser import ConfigParser
import sys
import asterisk
import asterisk.agi
from asterisk.agi import *
import socket
import os
import sys
config = ConfigParser()
config.read('/var/www/html/config.ini')
LOG_LEVEL = logging.info('LOGGING', 'level')
# Initialize logging
LOGGER = logging.getLogger('axi')
LOGGER.setLevel(logging.INFO)
formatter = logging.Formatter('|%(asctime)s|%(levelname)-8s|%(name)s|%(message)s')
log_file = logging.handlers.TimedRotatingFileHandler('/var/log/axi/input.csv', when='midnight', backupCount=7)
log_file.setLevel(logging.INFO)
log_file.setFormatter(formatter)
LOGGER.addHandler(log_file)
# Only print to console if at DEBUG level
if LOG_LEVEL == 'DEBUG':
log_console = logging.StreamHandler()
log_console.setLevel(logging.INFO)
log_console.formatter(formatter)
LOGGER.addHandler(log_console)
#BAUD = config.get('USB_Settings', 'baudrate')
#PTY = config.get('USB_Settings', 'parity')
#STPB = int(config.get('USB_Settings', 'stopbits'))
#BTSZ = int(config.get('USB_Settings', 'bytesize'))
HOST = config.get('Ethernet_Paging_System', 'IP')
PORT = config.get('Ethernet_Paging_System', 'Port')
agi = AGI()
pin = agi.env['agi_extension']
msg = agi.env['agi_calleridname']
geekspeak = {
"<ESC>": '\\x1b',
"<ETX>": '\\x03',
"<CR>": '\\r',
"<ACK>": '\\x06',
"<NAK>": '\\x15',
"<EOT>": '\\x04',
"<STX>": '\\x02'
}
htmlspeak = {
"<ESC>": '\\x1b',
"<ETX>": '\\x03',
"<CR>": '\\r',
"<ACK>": '\\x06',
"<NAK>": '\\x15',
"<EOT>": '\\x04',
"<STX>": '\\x02'
}
def str2geek(string):
geekstr = str(string)
for key, value in geekspeak.items():
if key in geekstr:
geekstr = geekstr.replace(key, value)
return geekstr
def geek2str(string):
sstr = str(string)
for key, value in geekspeak.items():
if value in sstr:
sstr = sstr.replace(value, key)
return sstr
def html2str(string):
hstr = str(string)
for key, value in htmlspeak.items():
if value in hstr:
hstr = hstr.replace(value, key)
return hstr
#Socket setup
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_INET, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except OSError as msg:
s = None
continue
try:
s.connect(sa)
except OSError as msg:
s.close()
s = None
continue
break
if s is None:
LOGGER.info('---Could not open socket')
sys.exit(1)
with s:
s.send(b'\\r')
sleep(0.5)
s.send(b'\\x1bPG1\\r')
strng=(pin)+(msg)
#New Code for Checksum
list_ascii=[ord(i) for i in strng]
#Prints each car decimal value
#print(list_ascii)
b=sum(list_ascii)+31
#Convert sum to 12 bit binary and parse to 4 sections frist 4 middle 4 last 4
h1=(bin(b)[2:].zfill(12)[8:])
h2=(bin(b)[2:].zfill(12)[4:8])
h3=(bin(b)[2:].zfill(12)[0:4])
#Adds 48 decimal value per TAP 1.8
i1=(int(h1, 2)+48)
i2=(int(h2, 2)+48)
i3=(int(h3, 2)+48)
#Gives checksum value
chks=chr(i3)+chr(i2)+chr(i1)
LOGGER.info('---Pin:' + pin + ' - ' + 'Message:' + msg + ' - checksum:' + chks)
s.send('\x02'.encode() + (pin).encode() + '\r'.encode() + msg.encode() + '\r\x03'.encode() + (chks).encode() + '\r'.encode())
resp=str(s.recv(1024))
if resp:
LOGGER.info(html2str(resp))
if '15' in resp:
LOGGER.info('page not accepted')
if resp:
sleep(0.5)
s.send(b'\x04\r')
sleep(0.5)
LOGGER.info('---Page Accepted' + ' - checksum:' + chks)
s.close()
我希望能夠創建一個使TCP套接字保持活動狀態的腳本,而另一個腳本將在對星號的調用上執行,並通過套接字或已運行的python腳本發送該數據,並開始使用變量發送數據的過程。
謝謝
這是我的方法。 我得到了第一個腳本來運行對星號的調用,第二個腳本打開連接並保持打開狀態,直到一側關閉為止。 星號腳本僅在呼叫進入星號時運行,並將入站SIP消息轉換為在護士呼叫行業大量使用的TAP 1.8消息。 我作為服務運行的套接字腳本打開了連接以發送數據。
星號腳本
#!/usr/bin/env python3
import serial
import re
from time import sleep
import sys
import asterisk
import asterisk.agi
from asterisk.agi import *
import socket
import os
geekspeak = {
"<ESC>": '\\x1b',
"<ETX>": '\\x03',
"<CR>": '\\r',
"<ACK>": '\\x06',
"<NAK>": '\\x15',
"<EOT>": '\\x04',
"<STX>": '\\x02'
}
htmlspeak = {
"<ESC>": '\\x1b',
"<ETX>": '\\x03',
"<CR>": '\\r',
"<ACK>": '\\x06',
"<NAK>": '\\x15',
"<EOT>": '\\x04',
"<STX>": '\\x02'
}
def str2geek(string):
geekstr = str(string)
for key, value in geekspeak.items():
if key in geekstr:
geekstr = geekstr.replace(key, value)
return geekstr
def geek2str(string):
sstr = str(string)
for key, value in geekspeak.items():
if value in sstr:
sstr = sstr.replace(value, key)
return sstr
def html2str(string):
hstr = str(string)
for key, value in htmlspeak.items():
if value in hstr:
hstr = hstr.replace(value, key)
return hstr
agi = AGI()
pin = '201' #agi.env['agi_extension']
msg = 'TEST' #agi.env['agi_calleridname']
strng=(pin)+(msg)
#New Code for Checksum
list_ascii=[ord(i) for i in strng]
#Prints each car decimal value
#print(list_ascii)
b=sum(list_ascii)+31
#Convert sum to 12 bit binary and parse to 4 sections frist 4 middle 4 last 4
h1=(bin(b)[2:].zfill(12)[8:])
h2=(bin(b)[2:].zfill(12)[4:8])
h3=(bin(b)[2:].zfill(12)[0:4])
#Adds 48 decimal value per TAP 1.8
i1=(int(h1, 2)+48)
i2=(int(h2, 2)+48)
i3=(int(h3, 2)+48)
#Gives checksum value
chks=chr(i3)+chr(i2)+chr(i1)
#Socket setup
s = None
for res in socket.getaddrinfo("localhost", 9988, socket.AF_INET, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except OSError as msg:
s = None
continue
try:
s.connect(sa)
except OSError as msg:
s.close()
s = None
continue
break
if s is None:
sys.exit(1)
with s:
s.send('\x02'.encode() + (pin).encode() + '\r'.encode() + msg.encode() + '\r\x03'.encode() + (chks).encode() + '\r'.encode())
s.close()
套接字腳本
#!/usr/bin/env python3
import serial
import re
from time import sleep
import logging
import logging.handlers
from configparser import ConfigParser
import socket
import os
import sys
config = ConfigParser()
config.read('/var/www/html/config.ini')
LOG_LEVEL = logging.info('LOGGING', 'level')
# Initialize logging
LOGGER = logging.getLogger('axi')
LOGGER.setLevel(logging.INFO)
formatter = logging.Formatter('|%(asctime)s|%(levelname)-8s|%(name)s|%(message)s')
log_file = logging.handlers.TimedRotatingFileHandler('/var/log/axi/input.csv', when='midnight', backupCount=7)
log_file.setLevel(logging.INFO)
log_file.setFormatter(formatter)
LOGGER.addHandler(log_file)
# Only print to console if at DEBUG level
if LOG_LEVEL == 'DEBUG':
log_console = logging.StreamHandler()
log_console.setLevel(logging.INFO)
log_console.formatter(formatter)
LOGGER.addHandler(log_console)
HOST = config.get('Ethernet_Paging_System', 'IP')
PORT = config.get('Ethernet_Paging_System', 'Port')
#Socket setup
s2 = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_INET, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s2 = socket.socket(af, socktype, proto)
except OSError as msg:
s2 = None
continue
try:
s2.connect(sa)
except OSError as msg:
s2.close()
s2 = None
continue
break
if s2 is None:
LOGGER.info('---Could not open socket')
sys.exit(1)
#listening Socket
s3 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s3.bind(("localhost", 9988))
s3.listen(1)
while True:
conn, addr = s3.accept()
data = conn.recv(1024)
if data:
#with s2:
s2.send(b'\\r')
sleep(0.5)
s2.send(b'\\x1bPG1\\r')
LOGGER.info(data)
s2.send(data)
resp=str(s2.recv(1024))
if resp:
# LOGGER.info(html2str(resp))
if '15' in resp:
LOGGER.info('page not accepted')
if resp:
s2.send(b'\x04\r')
LOGGER.info('---Page Accepted')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.