socket client server... simple example... not working...

Jean-Paul Calderone exarkun at divmod.com
Wed Oct 4 22:50:03 EDT 2006


On 4 Oct 2006 19:31:38 -0700, SpreadTooThin <bjobrien62 at gmail.com> wrote:
>client:
>
>import socket
>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>s.connect(("192.168.1.101", 8080))
>print 'Connected'
>s.send('ABCD')

Here you didn't check the return value of send to determine if all of the string was copied to the kernel buffer to be sent, so you may have only succeeded in sending part of 'ABCD'.

>buffer = s.recv(4)

in the above call, 4 is the maximum number of bytes recv will return.  It looks as though you are expecting it to return exactly 4 bytes, but in order to get that, you will need to check the length of the return value and call recv again with a lower limit until the combination of the return values of each call gives a total length of 4.

>print buffer
>s.send('exit')

Again, you didn't check the return value of send.

>
>
>server:
>
>serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>serversocket.bind(("192.168.1.101", 8080))
>serversocket.listen(5)
>print 'Listen'
>(clientsocket, address) = serversocket.accept()
>print 'Accepted'
>flag = True
>while flag:
>	chunk = serversocket.recv(4)

You're calling recv on serversocket instead of on clientsocket.  You're also relying on recv to return exactly 4 bytes, which it may not do.

>	if chunk == '':
>		raise RuntimeError, "socket connection broken"
>	elif chunk == 'exit':
>		flag = False
>	else:
>		serversocket.send(chunk)

Another missing check of the return value of send.

>print 'Done'
>
>Server says!
>
>Listen
>Accepted
>Traceback (most recent call last):
>  File "server.py", line 11, in ?
>    chunk = serversocket.recv(4)
>socket.error: (57, 'Socket is not connected')
>
>
>Client says:
>Connected
>
>What have I done wrong now!

I recommend switching to Twisted.  The Twisted equivalent (I guess - the protocol defined above is strange and complex (probably unintentionally, due to the things you left out, like any form of delimiter) and I doubt I really understand the end goal you are working towards), minus bugs (untested):

    # client.py
    from twisted.internet import reactor, protocol

    class Client(protocol.Protocol):
        buf = ''
        def connectionMade(self):
            self.transport.write('ABCD')
        def dataReceived(self, data):
            self.buf += data
            if len(self.buf) >= 4:
                reactor.stop()

    protocol.ClientCreator(reactor, Client).connectTCP('192.168.1.101', 8080)
    reactor.run()

    # server.py
    from twisted.internet import reactor, protocol
    
    class Server(protocol.Protocol):
        buf = ''
        def dataReceived(self, bytes):
            self.buf += bytes
            exit = self.buf.find('exit')
            if exit != -1:
                self.transport.write(self.buf[:exit])
                self.buf = self.buf[exit + 4:]
                reactor.stop()
            else:
                self.transport.write(self.buf)
                self.buf = ''

    f = protocol.ServerFactory()
    f.protocol = Server
    reactor.listenTCP('192.168.1.101', 8080, f)
    reactor.run()

Hope this helps,

Jean-Paul



More information about the Python-list mailing list