473,383 Members | 1,717 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

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

client:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.1.101", 8080))
print 'Connected'
s.send('ABCD')
buffer = s.recv(4)
print buffer
s.send('exit')
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)
if chunk == '':
raise RuntimeError, "socket connection broken"
elif chunk == 'exit':
flag = False
else:
serversocket.send(chunk)
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!

Oct 5 '06 #1
4 3234

Jean-Paul Calderone wrote:
On 4 Oct 2006 19:31:38 -0700, SpreadTooThin <bj********@gmail.comwrote:
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
Jean-Paul many thanks for this and your effort.
but why is it every time I try to do something with 'stock' python I
need another package?
By the time I've finished my project there are like 5 3rd party add-ons
to be installed.
I know I'm a python newbie... but I'm far from a developer newbie and
that can be a recipe for
disaster. The stock socket should work and I think I've missed an
obvious bug in the code other
than checking the return status.

Oct 5 '06 #2

Jean-Paul Calderone wrote:
On 5 Oct 2006 07:01:50 -0700, SpreadTooThin <bj********@gmail.comwrote:
[snip]

Jean-Paul many thanks for this and your effort.
but why is it every time I try to do something with 'stock' python I
need another package?

Maybe you are trying to do things that are too complex :)
No quite the contrary.. Which is why I want to keep it simple...
By the time I've finished my project there are like 5 3rd party add-ons
to be installed.

I don't generally find this to be problematic.
I have because it usually means makeing on many platforms...
Most of the time this is the nightmare.

I know I'm a python newbie... but I'm far from a developer newbie and
that can be a recipe for
disaster.

Not every library can be part of the standard library, neither can the
standard library satisfy every possible use-case. Relying on 3rd party
modules isn't a bad thing.
No but the less number of lines of code I have to support the better.

The stock socket should work and I think I've missed an
obvious bug in the code other
than checking the return status.
It was indeed as you said I was trying to read/write on the server
socket
not the client socket. (of the server module)

Well, I did mention one bug other than failure to check return values.
Maybe you missed it, since it was in the middle. Go back and re-read
my response.
Thanks again.
B.
Jean-Paul
Oct 5 '06 #3
SpreadTooThin wrote:
Jean-Paul many thanks for this and your effort.
but why is it every time I try to do something with 'stock' python I
need another package?
Twisted has it's fan, but you don't "need" it. Your code had a few
specific problems, and fixing them has little or nothing to do with
Twisted.
By the time I've finished my project there are like 5 3rd party add-ons
to be installed.
I know I'm a python newbie... but I'm far from a developer newbie and
that can be a recipe for
disaster. The stock socket should work and I think I've missed an
obvious bug in the code other
than checking the return status.
Obviously you wanted to recv() on your 'clientsocket' not your
'seversocket'. You can use sendall() to send all the given data;
it will raise an exception if it fails so there's no return code to
check. Since TCP is a stream protocol and does not have any concept
of message boundaries, you'll need to delimit messages within your
protocol, and call recv() until you have an entire message.
--
--Bryan
Oct 6 '06 #4
SpreadTooThin wrote:
but why is it every time I try to do something with 'stock' python I
need another package?
it's well known that all problems known to man can be solved by down-
loading Twisted, PyParsing, the Stream Editor, or that other programming
language that cannot be named.

</F>

Oct 6 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Michael Goettsche | last post by:
Hi there, I'm trying to write a simple server/client example. The client should be able to send text to the server and the server should distribute the text to all connected clients. However, it...
13
by: coloradowebdev | last post by:
i am working on basically a proxy server that handles requests via remoting from clients and executes transactions against a third-party server via TCP. the remoting site works like a champ. my...
6
by: J Rice | last post by:
Hi, I feel like I should apologize in advance because I must be missing something fairly basic and fundamental here. I don't have a book on Python network programming (yet) and I haven't been able...
10
by: Uma - Chellasoft | last post by:
Hai, I am new to VB.Net programming, directly doing socket programming. In C, I will be able to map the message arrived in a socket directly to a structure. Is this possible in VB.Net. Can...
9
by: zxo102 | last post by:
Hi everyone, I am using a python socket server to collect data from a socket client and then control a image location ( wxpython) with the data, i.e. moving the image around in the wxpython frame....
4
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket...
6
by: Sean | last post by:
Hi Everyone, My apologies for a somewhat dump question but I am really stuck. I have been working on this code for two days straight I am dont know what is wrong with it. when I run the code, All...
8
by: =?Utf-8?B?Sm9obg==?= | last post by:
Hi all, I am new to .net technologies. ASP.NET supports socket programming like send/receive in c or c++? I am developing web-site application in asp.net and code behind is Visual C#. In...
2
by: kodart | last post by:
Introduction Performance is the main concern to most server application developers. That’s why many of them anticipate using .NET platform to develop high performance server application regardless...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.