I am very new to this platform, do you have an example or possibly elaborate. What will eventually happen is the information of this tag will be changing from a data base.
from java.net import Socket
from java.io import PrintWriter, BufferedReader, InputStreamReader, OutputStreamWriter
from java.lang import Exception
import sys
def send_and_receive_multi_line(ip_address, port, message_to_send):
socket = None
reader = None
writer = None
response_lines = []
try:
# 1. Establish connection and set a timeout
socket = Socket(ip_address, port)
socket.setSoTimeout(5000) # Timeout in milliseconds (e.g., 5 seconds)
# 2. Get input and output streams and wrap them with Reader/Writer
writer = PrintWriter(OutputStreamWriter(socket.getOutputStream(), "UTF-8"), True)
reader = BufferedReader(InputStreamReader(socket.getInputStream(), "UTF-8"))
# 3. Send the single-line message with a line terminator
# The `println` method automatically adds a newline character
writer.println(message_to_send)
# Flush the stream to ensure data is sent immediately
writer.flush()
# 4. Read the multi-line response
# The loop will read line by line until `reader.readLine()` returns None,
# which indicates the end of the stream or the socket is closed by the server.
# This approach works best if the server closes the connection after sending the full response.
line = reader.readLine()
while line is not None:
response_lines.append(line)
line = reader.readLine()
except Exception as e:
print "Socket Error: %s" % e
# Handle specific exceptions as needed (e.g., timeout, connection refused)
finally:
# 5. Ensure resources are closed
if writer:
writer.close()
if reader:
reader.close()
if socket:
socket.close()
return "\n".join(response_lines)
# --- Example Usage ---
# Replace with your server's IP and Port
server_ip = "192.168.10.102"
server_port = 502
# Ensure your message ends with a terminator if the server expects a specific one.
# PrintWriter.println handles standard terminators.
message = "\02Telegram Type=Job\nJob ID=1\nRecipe Name=Standard Recipe\nProduct Serial Number=0815sub\03"
# Call the function
response = send_and_receive_multi_line(server_ip, server_port, message)
if response:
print "Received response:"
print response
else:
print "No response or an error occurred."
This is what I have found that works, where you see
message = "\02Telegram Type=Job\nJob ID=1\nRecipe Name=Standard Recipe\nProduct Serial Number=0815sub\03"
I am needing to replace the static text with a tag which will change every time the script is ran.