Needing help with sockets

Discussion in 'Python' started by Martin Dion, Jul 21, 2003.

  1. Martin Dion

    Martin Dion Guest


    i'm relatively new to python and I need help with a little program i

    What i want to do:

    I want to be able to connect on any port on a system and then send and
    receive commands, by following the protocol rules.

    If I receive data, it must print on the screen.

    It asks for data to send in reply to the data received.

    Once data is sent, it must look if there is data to receive and if not,
    it must ask the user to send an other string.

    The problem, is that once data is sent, it goes to the receive data loop
    and blocks until it gets data.

    I read a little on non-blocking sockets, but i am not sure if it is what
    i should look for

    I heard about timed sockets (maybe it could work, but i am unsure)

    import socket

    remote = raw_input('To wich host:')
    port = input('To wich port:')

    #remote = ""
    #port = 22

    while 1: # entering software main loop

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creating
    print "\nConnecting to:",remote,":",port

    s.connect((remote, port))
    print "\nConnected to:",remote,":",port

    while 1: #Net main loop

    while 1: #receiving data

    data = s.recv(1000)
    print data
    if len(data) < 1000: break #no more data to get so break

    toSend = raw_input("Data to Send:")
    if toSend == "!QUIT" :break

    del s
    Martin Dion, Jul 21, 2003
    1. Advertisements

  2. I'm not sure what you mean with 'select module for a client'...
    What do you need to know that is not in the module documentation
    or the Python socket howto?

    Anyway have a look at the following mini example that I whipped up:

    from select import select
    from socket import *
    import sys

    sock=socket(AF_INET, SOCK_STREAM)
    sock.connect( ('', 21) ) # ftp port

    print '>', # prompt

    while 1:
    ins, outs, exs = select([sys.stdin, sock], [], [])
    if sys.stdin in ins:
    print '>',
    if sock in ins:
    socketdata=sock.recv(1000) # buffer = 1000
    if socketdata:
    print socketdata,
    break # no more data


    Does this help? If not, please describe in more detail what you
    want to achive, what you've already tried and why that didn't work.

    Good luck!

    --Irmen de Jong
    Irmen de Jong, Jul 24, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.