473,788 Members | 2,800 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

client:

import socket
s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
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(s ocket.AF_INET, socket.SOCK_STR EAM)
serversocket.bi nd(("192.168.1. 101", 8080))
serversocket.li sten(5)
print 'Listen'
(clientsocket, address) = serversocket.ac cept()
print 'Accepted'
flag = True
while flag:
chunk = serversocket.re cv(4)
if chunk == '':
raise RuntimeError, "socket connection broken"
elif chunk == 'exit':
flag = False
else:
serversocket.se nd(chunk)
print 'Done'

Server says!

Listen
Accepted
Traceback (most recent call last):
File "server.py" , line 11, in ?
chunk = serversocket.re cv(4)
socket.error: (57, 'Socket is not connected')
Client says:
Connected

What have I done wrong now!

Oct 5 '06 #1
4 3258

Jean-Paul Calderone wrote:
On 4 Oct 2006 19:31:38 -0700, SpreadTooThin <bj********@gma il.comwrote:
client:

import socket
s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
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(s ocket.AF_INET, socket.SOCK_STR EAM)
serversocket.bi nd(("192.168.1. 101", 8080))
serversocket.li sten(5)
print 'Listen'
(clientsocket, address) = serversocket.ac cept()
print 'Accepted'
flag = True
while flag:
chunk = serversocket.re cv(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.se nd(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.re cv(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.interne t import reactor, protocol

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

protocol.Client Creator(reactor , Client).connect TCP('192.168.1. 101', 8080)
reactor.run()

# server.py
from twisted.interne t import reactor, protocol

class Server(protocol .Protocol):
buf = ''
def dataReceived(se lf, 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.Server Factory()
f.protocol = Server
reactor.listenT CP('192.168.1.1 01', 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********@gma il.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
2322
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 seems that only the first entered text is sent and received. When I then get prompted for input again and press return, nothing gets back to me. Any hints on what I have done would be very much appreciated! Here's my code:
13
2649
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 problem is executing the transactions against the remote server and returning the response to the remoting client. i can open the socket fine and, if i am executing one transaction at a time, everything works great. it's when my proxy server...
6
9801
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 to find an answer on the net so far. I am trying to create a pair of programs, one (the client) will be short-lived (fairly) and the second (server) will act as a cache for the client. Both will run on the same machine, so I think a simple...
10
4043
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 anyone please help me with some sample codings and guidance? Can you also suggest some other news group available for socket programming in VB.Net?
9
5556
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. But the "app.MainLoop()" in wxpython looks like conflicting with the "while 1:" in socket server. After I commented the "app.MainLoop()", everything is working except two things: 1. if I click anywhere on the screen with the mouse, the image is...
4
3605
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 client and asynchronous socket server example code provided in the .NET framework developers guide is a great start but I have not dealt with sockets before and I am struggling with something. From what I can tell the sample server code ...
6
2852
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 I get is Input: and the program quits. I also tried reading this online but I didn't quite get it. What is the diff between sin_addr and sin_addr.s_addr. My understanding is that the latter is the IP address of my machine where as the former is...
8
4685
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 page_load event, I am using atl com component. Here one for loop is there. In this for loop, number of iterations are 1000, I can receive some data using com component. It is just set of some characters like
2
18381
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 of the security features it provides. Microsoft Windows provides a high performance model that uses I/O completion port (IOCP) to process network events. IOCP provides best performance, but difficult to use due to lack of good code samples and...
0
10364
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.