import socket
import threading
import queue
class SocketServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.message_queue = queue.Queue()
self.clients = {}
def start(self):
self.server.bind((self.host, self.port))
self.server.listen(5)
print(f"Server listening on {self.host}:{self.port}")
threading.Thread(target=self.accept_clients).start()
def accept_clients(self):
while True:
client_socket, address = self.server.accept()
print(f"Accepted connection from {address}")
self.clients[address] = client_socket
threading.Thread(target=self.client_handler, args=(client_socket, address)).start()
def client_handler(self, client_socket, address):
while True:
try:
data = client_socket.recv(1024)
if not data:
print(f"Connection closed by {address}")
break
self.message_queue.put((address, data))
print(f"Received data from {address}: {data.decode()}")
except ConnectionResetError:
print(f"Connection reset by {address}")
break
except Exception as e:
print(f"Exception from {address}: {e}")
break
client_socket.close()
del self.clients[address]
print(f"Closed connection with {address}")
def send_message(self, address, message):
if address in self.clients:
try:
client_socket = self.clients[address]
client_socket.sendall(message.encode())
print(f"Sent data to {address}: {message}")
except Exception as e:
print(f"Failed to send message to {address}: {e}")
else:
print(f"No active connection found for {address}")
if __name__ == '__main__':
server = SocketServer()
server.start()
# Add your logic here to manage message_queue or initiate communication
# For demonstration, send a message to a specific client after some delay
import time
def send_delayed_message():
time.sleep(10) # Wait for 10 seconds
if server.clients:
address = next(iter(server.clients.keys())) # Get the first client address
server.send_message(address, "Hello from server after delay!")
threading.Thread(target=send_delayed_message).start()
import socket
import threading
import queue
class SingleClientServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.message_queue = queue.Queue()
self.client_socket = None
self.client_address = None
def start(self):
self.server.bind((self.host, self.port))
self.server.listen(1) # Listen for only one connection
print(f"Server listening on {self.host}:{self.port}")
self.accept_client()
def accept_client(self):
while True:
print("Waiting for a connection...")
self.client_socket, self.client_address = self.server.accept()
print(f"Accepted connection from {self.client_address}")
self.handle_client()
def handle_client(self):
try:
while True:
data = self.client_socket.recv(1024)
if not data:
print(f"Connection closed by {self.client_address}")
break
self.message_queue.put((self.client_address, data))
print(f"Received data from {self.client_address}: {data.decode()}")
# Example: Sending the same data back to the client
self.send_message(data.decode()) # Echo the received message
except ConnectionResetError:
print(f"Connection reset by {self.client_address}")
except Exception as e:
print(f"Exception from {self.client_address}: {e}")
finally:
self.client_socket.close()
self.client_socket = None
self.client_address = None
def send_message(self, message):
if self.client_socket:
try:
self.client_socket.sendall(message.encode())
print(f"Sent message to {self.client_address}: {message}")
except Exception as e:
print(f"Failed to send message to {self.client_address}: {e}")
if __name__ == '__main__':
server = SingleClientServer()
server_thread = threading.Thread(target=server.start)
server_thread.start()
# Example logic to send a message to the client every few seconds:
import time
def message_sender():
while True:
if server.client_socket:
server.send_message("Message from server")
time.sleep(5) # Wait for 5 seconds before sending the next message
sender_thread = threading.Thread(target=message_sender)
sender_thread.start()
def init(ContextInfo):
server = SingleClientServer()
server_thread = threading.Thread(target=server.start)
server_thread.start()
# Example logic to send a message to the client every few seconds:
import time
code
def message_sender():
while True:
if server.client_socket:
server.send_message("Message from server")
time.sleep(5) # Wait for 5 seconds before sending the next message
sender_thread = threading.Thread(target=message_sender)
sender_thread.start()
调用stop后再次启动 提示 【2024-11-19 15:52:36.588】 0D:\迅投极速交易终端 睿智融科版\python\新建策略文件4.py_SH00030048IndentationError:unindent does not match any outer indentation level (, line 9)
import socket
import threading
import queue
class SingleClientServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.message_queue = queue.Queue()
self.client_socket = None
self.client_address = None
self.running = False
def start(self):
self.server.bind((self.host, self.port))
self.server.listen(1) # Listen for only one connection
self.running = True
print(f"Server listening on {self.host}:{self.port}")
self.accept_client()
def accept_client(self):
try:
while self.running:
print("Waiting for a connection...")
self.client_socket, self.client_address = self.server.accept()
print(f"Accepted connection from {self.client_address}")
self.handle_client()
except Exception as e:
print(f"Server accept loop error: {e}")
def handle_client(self):
buffer = ""
try:
while self.running and self.client_socket:
data = self.client_socket.recv(1024)
if not data:
print(f"Connection closed by {self.client_address}")
break
buffer += data.decode()
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
self.message_queue.put((self.client_address, line))
print(f"Received line from {self.client_address}: {line}")
# Example: Echo the received line back to the client
self.send_message(line)
except ConnectionResetError:
print(f"Connection reset by {self.client_address}")
except Exception as e:
print(f"Exception from {self.client_address}: {e}")
finally:
if self.client_socket:
self.client_socket.close()
self.client_socket = None
self.client_address = None
def send_message(self, message):
if self.client_socket:
try:
self.client_socket.sendall((message + "\n").encode())
print(f"Sent message to {self.client_address}: {message}")
except Exception as e:
print(f"Failed to send message to {self.client_address}: {e}")
def stop(self):
print("Stopping server...")
self.running = False
if self.client_socket:
self.client_socket.close()
self.server.close()
if __name__ == '__main__':
server = SingleClientServer()
server_thread = threading.Thread(target=server.start)
server_thread.start()
# Example logic to stop the server after some time
import time
def shutdown_server():
time.sleep(30) # Let the server run for 30 seconds
server.stop()
print("Server has been stopped.")
shutdown_thread = threading.Thread(target=shutdown_server)
shutdown_thread.start()
import socket
import threading
import queue
class SingleClientServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.message_queue = queue.Queue()
self.client_socket = None
self.client_address = None
self.running = False
def start(self):
self.server.bind((self.host, self.port))
self.server.listen(1) # Listen for only one connection
self.running = True
print(f"Server listening on {self.host}:{self.port}")
self.accept_client()
def accept_client(self):
try:
while self.running:
print("Waiting for a connection...")
self.client_socket, self.client_address = self.server.accept()
print(f"Accepted connection from {self.client_address}")
self.handle_client()
except Exception as e:
print(f"Server accept loop error: {e}")
finally:
self.cleanup()
def handle_client(self):
buffer = ""
try:
while self.running and self.client_socket:
data = self.client_socket.recv(1024)
if not data:
print(f"Connection closed by {self.client_address}")
break
buffer += data.decode()
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
self.message_queue.put((self.client_address, line))
print(f"Received line from {self.client_address}: {line}")
# Echo the received line back to the client
self.send_message(line)
except ConnectionResetError:
print(f"Connection reset by {self.client_address}")
except Exception as e:
print(f"Exception from {self.client_address}: {e}")
finally:
self.cleanup()
def send_message(self, message):
if self.client_socket:
try:
self.client_socket.sendall((message + "\n").encode())
print(f"Sent message to {self.client_address}: {message}")
except Exception as e:
print(f"Failed to send message to {self.client_address}: {e}")
def stop(self):
print("Stopping server...")
self.running = False
if self.client_socket:
self.client_socket.close()
self.server.close()
def cleanup(self):
if self.client_socket:
self.client_socket.close()
self.client_socket = None
self.client_address = None
def external_control_stop(server):
# Custom logic to determine when to stop
import time
time.sleep(10) # Wait for 10 seconds, simulating some conditions or tasks
server.stop()
print("Server has been stopped by external control.")
if __name__ == '__main__':
server = SingleClientServer()
server_thread = threading.Thread(target=server.start)
server_thread.start()
# Start external control which will eventually call server.stop()
control_thread = threading.Thread(target=external_control_stop, args=(server,))
control_thread.start()
import socket
import threading
import queue
import time
class SingleClientServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.message_queue = queue.Queue()
self.client_socket = None
self.client_address = None
self.running = False
def start(self):
self.server.bind((self.host, self.port))
self.server.listen(1) # Listen for only one connection
self.running = True
print(f"Server listening on {self.host}:{self.port}")
self.accept_client()
def accept_client(self):
try:
while self.running:
print("Waiting for a connection...")
self.client_socket, self.client_address = self.server.accept()
print(f"Accepted connection from {self.client_address}")
self.handle_client()
except Exception as e:
print(f"Server accept loop error: {e}")
finally:
self.cleanup()
def handle_client(self):
buffer = ""
try:
while self.running and self.client_socket:
data = self.client_socket.recv(1024)
if not data:
print(f"Connection closed by {self.client_address}")
break
buffer += data.decode()
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
self.message_queue.put((self.client_address, line))
print(f"Received line from {self.client_address}: {line}")
# Echo the received line back to the client
self.send_message(line)
except ConnectionResetError:
print(f"Connection reset by {self.client_address}")
except Exception as e:
print(f"Exception from {self.client_address}: {e}")
finally:
self.cleanup()
def send_message(self, message):
if self.client_socket:
try:
self.client_socket.sendall((message + "\n").encode())
print(f"Sent message to {self.client_address}: {message}")
except Exception as e:
print(f"Failed to send message to {self.client_address}: {e}")
def stop(self):
print("Stopping server...")
self.running = False
if self.client_socket:
self.client_socket.close()
self.server.close()
def cleanup(self):
if self.client_socket:
self.client_socket.close()
self.client_socket = None
self.client_address = None
# Initialize the server and store the reference in ContextInfo
def init(ContextInfo):
server = SingleClientServer()
ContextInfo['server'] = server # Store server in ContextInfo for later access
server_thread = threading.Thread(target=server.start)
server_thread.start()
# Example logic to send a message to the client every few seconds:
def message_sender():
while server.running:
if server.client_socket:
server.send_message("Message from server")
time.sleep(5) # Wait for 5 seconds before sending the next message
sender_thread = threading.Thread(target=message_sender)
sender_thread.start()
# Stop the server using the reference from ContextInfo
def stop(ContextInfo):
server = ContextInfo.get('server')
if server:
server.stop()
print("Stopped")
# Example usage
if __name__ == '__main__':
ContextInfo = {}
init(ContextInfo)
time.sleep(30) # Let the server run for 30 seconds for demonstration
stop(ContextInfo)
import socket
import threading
import queue
import time
class SingleClientServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.message_queue = queue.Queue()
self.client_socket = None
self.client_address = None
self.running = False
def start(self):
self.server.bind((self.host, self.port))
self.server.listen(1) # Listen for only one connection
self.running = True
print(f"Server listening on {self.host}:{self.port}")
self.accept_client()
def accept_client(self):
try:
while self.running:
print("Waiting for a connection...")
self.client_socket, self.client_address = self.server.accept()
print(f"Accepted connection from {self.client_address}")
self.handle_client()
except Exception as e:
print(f"Server accept loop error: {e}")
finally:
self.cleanup()
def handle_client(self):
buffer = ""
try:
while self.running and self.client_socket:
data = self.client_socket.recv(1024)
if not data:
print(f"Connection closed by {self.client_address}")
break
buffer += data.decode()
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
self.message_queue.put((self.client_address, line))
print(f"Received line from {self.client_address}: {line}")
# Echo the received line back to the client
self.send_message(line)
except ConnectionResetError:
print(f"Connection reset by {self.client_address}")
except Exception as e:
print(f"Exception from {self.client_address}: {e}")
finally:
self.cleanup()
def send_message(self, message):
if self.client_socket:
try:
self.client_socket.sendall((message + "\n").encode())
print(f"Sent message to {self.client_address}: {message}")
except Exception as e:
print(f"Failed to send message to {self.client_address}: {e}")
def stop(self):
print("Stopping server...")
self.running = False
if self.client_socket:
self.client_socket.close()
self.server.close()
def cleanup(self):
if self.client_socket:
self.client_socket.close()
self.client_socket = None
self.client_address = None
# Initialize the server and store the reference in ContextInfo
def init(ContextInfo):
server = SingleClientServer()
ContextInfo['server'] = server # Store server in ContextInfo for later access
server_thread = threading.Thread(target=server.start)
server_thread.start()
# Example logic to send a message to the client every few seconds:
def message_sender():
while server.running:
if server.client_socket:
server.send_message("Message from server")
time.sleep(5) # Wait for 5 seconds before sending the next message
sender_thread = threading.Thread(target=message_sender)
sender_thread.start()
# Stop the server using the reference from ContextInfo
def stop(ContextInfo):
server = ContextInfo.get('server')
if server:
server.stop()
print("Stopped")
# Example usage
if __name__ == '__main__':
ContextInfo = {}
init(ContextInfo)
time.sleep(30) # Let the server run for 30 seconds for demonstration
stop(ContextInfo)