You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PsychoPy双脚本TCP通信故障:发送端消息无法抵达接收端

PsychoPy TCP跨脚本通信故障排查

目标

  • 基于PsychoPy开发双人协作心理实验,实现两台电脑上的脚本通过TCP通信传递信号,当前优先完成脚本A向脚本B发送信号的基础功能。

问题

脚本A可正常将信号发送至服务器,但脚本B始终无法接收消息。服务器命令行可确认消息已到达,但接收端脚本的接收循环持续报错。

预期效果

  • 脚本A通过对话框获取用户输入,通过线程将信号发送至服务器
  • 服务器接收消息后转发至脚本B

已尝试操作

  • 参考网络上可正常运行的「服务器+双客户端」TCP通信架构代码进行修改适配
  • 两台电脑均能成功连接服务器,服务器可打印收到的信号,但接收端脚本持续报错

环境配置

  • 操作系统:Win10
  • PsychoPy版本:2020.2.5 64位(标准独立版)
  • Python版本:3.10
  • 部署方式:两台电脑分别运行发送端、接收端脚本,均连接同一服务器

代码实现

发送端客户端(PsychoPy)

from psychopy import visual, event, core, data 
from psychopy.visual import textbox #import textbox library for textual stimuli
import threading
import socket
from psychopy import gui
from psychopy import __version__ 

# Connecting To Server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 5005))

def write():
    while True:
        message = str(signal)
        client.send(message.encode('ascii'))

# Create dialogbox to record the signal
dlg = gui.Dlg(title="My experiment", pos=(200, 400))
dlg.addText('Make your decision', color='Blue')
dlg.addField('Decision:', tip='or subject code')
signal = dlg.show()

if dlg.OK:
    print(signal)
else:
    print('User cancelled')

write_thread = threading.Thread(target=write)
write_thread.start()

服务器(基础Python)

import threading
import socket

host = 'localhost' # localhost
port = 5005

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.settimeout(20) #I tried to increase allowed time before timeout but it doesn't help
server.listen()

clients = []
signals = []

# Sending Messages To All Connected Clients
def broadcast(signal):
    for client in clients:
        client.send(signal)
        print(signal) #to check if the signal even reaches the server and it does

# Handling Messages From Clients
def handle(client):
    while True:
        try:
            # Broadcasting Messages
            signal = client.recv(1024)
            broadcast(signal)
        except:
            # Removing And Closing Clients
            index = clients.index(client)
            clients.remove(client)
            client.close()
            signal = signals[index]
            broadcast(signal.encode('ascii'))
            signals.remove(signal)
            break

# Receiving / Listening Function
def receive():
    while True:
        # Accept Connection
        client, address = server.accept()
        print("Connected with {}".format(str(address)))

        signal = client.recv(1024).decode('ascii')
        signals.append(signal)
        clients.append(client)

        broadcast(signal.encode('ascii'))
        client.send('Connected to server!'.encode('ascii'))

        # Start Handling Thread For Client
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()


print("Server is listening...")
receive()

接收端客户端(PsychoPy)

from psychopy import visual, event, core, data 
from psychopy.visual import textbox #import textbox library for textual stimuli
import threading
import socket
from psychopy import gui
from psychopy import __version__

win = visual.Window(screen =0, fullscr = False, allowGUI=True, units='pix', color = 'black')

# Connecting To Server
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 5005))

# Listening to Server
def receive():
    while True:
        try:
            # Receive Message From Server
            signal = client.recv(1024).decode('ascii')
            if signal is not None:
                message = visual.TextStim(win, str(signal))
                message.draw()
                win.flip()
                print(signal) #To make sure, the signal was received but it never happens
                
        except:  
            # Close Connection When Error
            print("An error occured!")   #This always happens when I run it 
            client.close()
            break


# Starting Thread For Listening
receive_thread = threading.Thread(target=receive)
receive_thread.start()

event.waitKeys()

内容的提问来源于stack exchange,提问作者HauchTüll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 00:14:56