1

我对套接字编程完全陌生。我有一个产品并试图连接。我可以发送数据并在产品上查看其结果,但我收不到任何东西。这是我的脚本:

import socket
def ScktConn():
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect(('127.0.0.1', 5006))
# our local IP is 192.168.2.1, but it works even with 127.0.0.1, I don't know from where       #it is coming
 Freq=raw_input('Frequency(450-2500): ')
 CmdF='0 ace_set_frequency C1 '+str(Freq)+' \r\n'
 s.send(CmdF)
# so far I sent a tcl command to product to set the frequency and it works
 s.send('0 ace_azplayer_remove_player XXX \r\n')
# sending another tcl command and works
 s.send('0 ace_azplayer_add_player \r\n')
# here it is working too
 s.send('0 ace_azplayer_add_ace XXX C1\r\n')
 Path='C:/Users/AM_RJ/Desktop/gridview_script/PBF/4x4U_wocorr_SNR.csv'
 s.send('0 ace_azplayer_load_csvfile AzPlayer1 '+Path+' \r\n')
# here I should receive some numbers, but always returning me 0!
#even if I send ('hello!') and use recv(1024), it returns 0!
 csvid=s.recv(4096)
 print csvid
 Path2='0 ace_azplayer_edit_playback_file AzPlayer1 '+str(csvid)+' -linkConfiguration "4x4" \r\n'
 print Path2
 s.send(Path2)

使用后recv(4096),我应该会收到一些号码,但它总是返回我0!即使我发送('hello!')使用recv(1024),它也会返回0!我正在使用python 2.7。我什至不确定服务器端和客户端在我的脚本中是否正确!请帮帮我。

4

1 回答 1

3

您需要多个套接字,这是一个最小的示例(需要更多工作才能使其健壮)。ScktConn 产生一个新线程,该线程创建一个服务器套接字,用于侦听来自s.

import socket
import threading
import time

address = ('127.0.0.1', 5007)
def ScktRecv():
    r = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    r.bind(address)
    r.listen(1)
    conn, _ = r.accept()
    csvid = conn.recv(4096)
    print "recv: %s" % csvid

def ScktConn():
    recv_thread = threading.Thread(target=ScktRecv)
    recv_thread.start()
    time.sleep(1)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(address)
    # our local IP is 192.168.2.1, but it works even with 127.0.0.1, I don't know from where       #it is coming
    Freq=raw_input('Frequency(450-2500): ')
    CmdF='0 ace_set_frequency C1 '+str(Freq)+' \r\n'
    s.send(CmdF)
于 2012-12-19T17:10:11.083 回答