[Update] WebSocket configuration: Change host to 127.0.0.1 and port to 2231; refactor WebSocket server initialization and message handling

This commit is contained in:
misyaguziya
2025-05-18 15:20:27 +09:00
parent ed5ebcee90
commit e7304247c7
4 changed files with 88 additions and 44 deletions

View File

@@ -965,6 +965,7 @@ class Config:
self.saveConfig(inspect.currentframe().f_code.co_name, value) self.saveConfig(inspect.currentframe().f_code.co_name, value)
@property @property
@json_serializable('WEBSOCKET_HOST')
def WEBSOCKET_HOST(self): def WEBSOCKET_HOST(self):
return self._WEBSOCKET_HOST return self._WEBSOCKET_HOST
@@ -975,6 +976,7 @@ class Config:
self.saveConfig(inspect.currentframe().f_code.co_name, value) self.saveConfig(inspect.currentframe().f_code.co_name, value)
@property @property
@json_serializable('WEBSOCKET_PORT')
def WEBSOCKET_PORT(self): def WEBSOCKET_PORT(self):
return self._WEBSOCKET_PORT return self._WEBSOCKET_PORT
@@ -1171,8 +1173,8 @@ class Config:
self._VRC_MIC_MUTE_SYNC = False self._VRC_MIC_MUTE_SYNC = False
self._NOTIFICATION_VRC_SFX = True self._NOTIFICATION_VRC_SFX = True
self._WEBSOCKET_SERVER = True self._WEBSOCKET_SERVER = True
self._WEBSOCKET_HOST = "0.0.0.0" self._WEBSOCKET_HOST = "127.0.0.1"
self._WEBSOCKET_PORT = 8765 self._WEBSOCKET_PORT = 2231
def load_config(self): def load_config(self):
if os_path.isfile(self.PATH_CONFIG) is not False: if os_path.isfile(self.PATH_CONFIG) is not False:

View File

@@ -298,7 +298,7 @@ class Controller:
if config.WEBSOCKET_SERVER is True: if config.WEBSOCKET_SERVER is True:
model.websocketSendMessage( model.websocketSendMessage(
{ {
"type":"SEND", "type":"SENT",
"message":message, "message":message,
"translation":translation, "translation":translation,
"transliteration":transliteration "transliteration":transliteration
@@ -466,11 +466,11 @@ class Controller:
} }
) )
# update textbox message log (Sent) # update textbox message log (Chat)
if config.LOGGER_FEATURE is True: if config.LOGGER_FEATURE is True:
if len(translation) > 0: if len(translation) > 0:
translation_text = " (" + "/".join(translation) + ")" translation_text = " (" + "/".join(translation) + ")"
model.logger.info(f"[SENT] {message}{translation_text}") model.logger.info(f"[CHAT] {message}{translation_text}")
return {"status":200, return {"status":200,
"result":{ "result":{
@@ -1840,8 +1840,8 @@ class Controller:
@staticmethod @staticmethod
def setEnableWebSocketServer(*args, **kwargs) -> dict: def setEnableWebSocketServer(*args, **kwargs) -> dict:
config.WEBSOCKET_SERVER = True
model.startWebSocketServer() model.startWebSocketServer()
config.WEBSOCKET_SERVER = True
return {"status":200, "result":config.WEBSOCKET_SERVER} return {"status":200, "result":config.WEBSOCKET_SERVER}
@staticmethod @staticmethod

View File

@@ -1,5 +1,7 @@
import copy import copy
import gc import gc
import asyncio
import json
from subprocess import Popen from subprocess import Popen
from os import makedirs as os_makedirs from os import makedirs as os_makedirs
from os import path as os_path from os import path as os_path
@@ -100,43 +102,10 @@ class Model:
self.kks = kakasi() self.kks = kakasi()
self.watchdog = Watchdog(config.WATCHDOG_TIMEOUT, config.WATCHDOG_INTERVAL) self.watchdog = Watchdog(config.WATCHDOG_TIMEOUT, config.WATCHDOG_INTERVAL)
self.osc_handler = OSCHandler(config.OSC_IP_ADDRESS, config.OSC_PORT) self.osc_handler = OSCHandler(config.OSC_IP_ADDRESS, config.OSC_PORT)
self.websocket_server = None
# WebSocketサーバーの初期化 self.websocket_server_loop = False
self.websocket_server = WebSocketServer( self.websocket_server_alive = False
host=config.WEBSOCKET_HOST, self.th_websocket_server = None
port=config.WEBSOCKET_PORT
)
def startWebSocketServer(self):
try:
self.websocket_server.start()
except Exception:
errorLogging()
def stopWebSocketServer(self):
if self.websocket_server:
try:
self.websocket_server.stop()
except Exception:
errorLogging()
def checkWebSocketServer(self):
if self.websocket_server:
try:
return self.websocket_server.is_running
except Exception:
errorLogging()
return False
def websocketSendMessage(self, message):
"""
WebSocketサーバーから全クライアントにメッセージを送信する
:param message: 送信するメッセージ
"""
try:
self.websocket_server.send(str(message))
except Exception:
errorLogging()
def checkTranslatorCTranslate2ModelWeight(self, weight_type:str): def checkTranslatorCTranslate2ModelWeight(self, weight_type:str):
return checkCTranslate2Weight(config.PATH_LOCAL, weight_type) return checkCTranslate2Weight(config.PATH_LOCAL, weight_type)
@@ -865,4 +834,77 @@ class Model:
self.th_watchdog.join() self.th_watchdog.join()
self.th_watchdog = None self.th_watchdog = None
def startWebSocketServer(self):
"""WebSocketサーバーを起動し、別スレッドで実行する"""
self.websocket_server_loop = True
self.websocket_server_alive = False # 初期状態を明示
async def WebSocketServerMain():
try:
self.websocket_server = WebSocketServer(
host=config.WEBSOCKET_HOST,
port=config.WEBSOCKET_PORT,
)
self.websocket_server.start()
self.websocket_server_alive = True
# イベントループが終了するまで待機
while self.websocket_server_loop:
self.websocket_server.send("Server is running...")
await asyncio.sleep(0.5) # 応答性向上のため間隔短縮
except Exception:
errorLogging()
# 具体的なエラー内容をログに残す場合
# self.logger.error(f"WebSocket server error: {str(e)}")
finally:
# 確実にサーバーを停止
if hasattr(self, 'websocket_server') and self.websocket_server:
self.websocket_server.stop()
self.websocket_server_alive = False
self.th_websocket_server = Thread(target=lambda: asyncio.run(WebSocketServerMain()))
self.th_websocket_server.daemon = True
self.th_websocket_server.start()
def stopWebSocketServer(self):
"""WebSocketサーバーを停止する"""
if not hasattr(self, 'th_websocket_server') or self.th_websocket_server is None:
return
self.websocket_server_loop = False
try:
# 一定時間待機してからタイムアウト
self.th_websocket_server.join(timeout=2.0)
if self.th_websocket_server.is_alive():
# タイムアウト後もスレッドが生きている場合の処理
self.logger.warning("WebSocket server thread did not terminate properly")
except Exception:
errorLogging()
finally:
self.th_websocket_server = None
self.websocket_server = None
self.websocket_server_alive = False
def checkWebSocketServer(self):
"""WebSocketサーバーの稼働状態を確認する"""
return self.websocket_server_alive
def websocketSendMessage(self, message_dict:dict):
"""
WebSocketサーバーから全クライアントにメッセージを送信する
:param message_dict: 送信するメッセージの辞書
:return: 送信成功したかどうか
"""
if not self.websocket_server_alive or not self.websocket_server:
return False
try:
message_json = json.dumps(message_dict)
return self.websocket_server.send(message_json)
except Exception:
errorLogging()
return False
model = Model() model = Model()

View File

@@ -14,7 +14,7 @@ class WebSocketServer:
- メッセージのブロードキャスト機能 - メッセージのブロードキャスト機能
- GUIスレッド等からメッセージ送信するためのキュー - GUIスレッド等からメッセージ送信するためのキュー
""" """
def __init__(self, host: str='localhost', port: int=8765): def __init__(self, host: str='127.0.0.1', port: int=8765):
""" """
サーバーのホスト名とポートを指定して初期化します。 サーバーのホスト名とポートを指定して初期化します。
""" """