Sonic
Sonic

Reputation: 85

Client/Server Not Receiving Data in Python

I am totally new to socket programming. I have a product and trying to connect. I can send the data and see its result on product, but I cannot receive anything. this is my script:

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)

After using recv(4096), I should receive some numbers, but it always returning me 0! even if I send ('hello!') and use recv(1024), it returns 0! I'm using python 2.7. I am not even sure whether or not the server and client sides are correct in my script! Please help me out about it.

Upvotes: 2

Views: 1812

Answers (1)

cmh
cmh

Reputation: 10927

You need more than one socket, here is a minimal example (which would need more work to be made robust). ScktConn spawns a new thread which creates a server socket that listens for the connection from 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)

Upvotes: 3

Related Questions