473,703 Members | 2,660 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with socket

My problem is not really python specific but as I do my implementation
in python I hope someone here can help me.

I have two programs that talk through a socket. Here is the code :

<server>
sock = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
sock.setsockopt (socket.SOL_SOC KET, socket.SO_REUSE ADDR, 1)

sock.settimeout (5.0)

sock.bind(("", port)
# We only handle one connection
sock.listen(1)

while 1:
newsock, address = sock.accept()
handle(newsock, address)

def handle(sock, address) :
print "Connection from", address
dataReceived = newsock.recv(10 24)
while 1:
try:
newsock.send(da ta)
except socket.timeout, err:
print "Connection timeout %s" % err
break
except socket.error, err:
print "Connection broken %s" % err
break

</server>

<client>
sock = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
sock.settimeout (5.0)
sock.connect((h ost, port))
sock.send("Gimm e a piece of information, please\r\n")

while 1:
r, w, e = select.select([s], [], [], 1.0)
if r != []:
handle_connecti on(s)
def handle_connecti on(sock):
try:
response_data = sock.recv(1024)
except socket.timeout:
print "Socket timeout"
return
manage(response _data)

</client>

Ok I hope it's clear. My problem is that "select" only tests if there's
data on the socket, and not the state of the socket. I want to be able
to know if socket is "alive" or something like that. But I don't want
to make "send" in the client (stay passive). Then, if I know that my
socket is closed or my link down, I can try to reconnect periodically.

I would rewrite the while in the client like that :
<client>
while 1:
if not test_connect(s) :
reconnect(s)
# else continue normally
r, w, e = select.select([s], [], [], 1.0)
if r != []:
handle_connecti on(s)
</client

My env: python2.3, linux/win32.

Thanks in advance,

--
Thomas Herve <sorry for my english>
Jul 18 '05 #1
3 2648
In article <40************ ***********@new s.free.fr>,
Thomas Herve <th****@neocles .com> wrote:
....
Ok I hope it's clear. My problem is that "select" only tests if there's
data on the socket, and not the state of the socket. I want to be able
to know if socket is "alive" or something like that. But I don't want
to make "send" in the client (stay passive). Then, if I know that my
socket is closed or my link down, I can try to reconnect periodically.


Try a SO_KEEPALIVE option on the socket (setsockopt). That
should (I would sort of expect anyway) raise an exception when
the keepalive negotiation fails. The reaction won't be immediate,
it may take hours to notice a dead connection.

Donn Cave, do**@u.washingt on.edu
Jul 18 '05 #2
On 2004-04-28, Thomas Hervé <th****@neocles .com> wrote:
Ok I hope it's clear. My problem is that "select" only tests
if there's data on the socket, and not the state of the
socket.
That's not true. If the socket is closed, it will return from
select as readable.
I want to be able to know if socket is "alive" or something
like that. But I don't want to make "send" in the client (stay
passive). Then, if I know that my socket is closed or my link
down, I can try to reconnect periodically.


You'll know if the socket is closed because select will mark it
as readable, and you'll get 0 bytes when you read it.

If you want to know if the network or the other host has "gone
away", set the SO_KEEPALIVE option on the socket. That will
generate an error if the link is down. IIRC, it takes 75
minutes (or is it 150?) to time out after the other end goes
away.

--
Grant Edwards grante Yow! I wonder if there's
at anything GOOD on tonight?
visi.com
Jul 18 '05 #3
Grant Edwards wrote:
On 2004-04-28, Thomas Hervé <th****@neocles .com> wrote:

Ok I hope it's clear. My problem is that "select" only tests
if there's data on the socket, and not the state of the
socket.
That's not true. If the socket is closed, it will return from
select as readable.


Exact.
I want to be able to know if socket is "alive" or something
like that. But I don't want to make "send" in the client (stay
passive). Then, if I know that my socket is closed or my link
down, I can try to reconnect periodically.


You'll know if the socket is closed because select will mark it
as readable, and you'll get 0 bytes when you read it.


It seems that it's not true : when I read it I have a "Connection reset
by peer" error.
If you want to know if the network or the other host has "gone
away", set the SO_KEEPALIVE option on the socket. That will
generate an error if the link is down. IIRC, it takes 75
minutes (or is it 150?) to time out after the other end goes
away.


Yes, I've seen this option, but the delay is a bit too large (2 hours ?
depending on OS it seems) and not configurable. So I made it by send
some hearbeat regulary, even if I didn't want to I haven't found another
way. And it's better for server side, from which I can make some recv
that make the break found earlier.

--
Thomas Herve
Jul 18 '05 #4

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

Similar topics

0
1445
by: Gonçalo Rodrigues | last post by:
Hi, I have a problem with threads and sockets. I'll try to describe the problem in words with pseudo-code. I've been working on a few classes to make it easier to work with threads. This framework, let us call it that, consists in two parts. The first part is just a basic thread class deriving from threading.Thread with a few extra functionality that makes it easier for a thread to spawn a new thread and "father it". Each of its
4
2350
by: Sa¹o Zagoranski | last post by:
Hi! I'm writing a simple 3D First person shooter game. It is a multiplayer game, where all the players connect to one server.
4
8198
by: yaron | last post by:
Hi, I have a problem when sending data over TCP socket from c# client to java server. the connection established ok, but i can't send data from c# client to java server. it's work ok with TcpClient, NetworkStream and StreamWriter classes. but with low level socket it doesn't work (When using the Socket class Send method).
0
1459
by: Usman | last post by:
Hi I'm having problem with a scenarion where I have a server written in C# and client written in VC6++. Here is the server code that i'm using including the Callback function for handling clients. Also there's a commented code where i'm using TCPListener instead of simple Socket Class. The problem i'm having is that when I run this code using Socket class, the server starts well but "OnClientConnect" method never gets called. On...
2
1987
by: Changhao | last post by:
Hi, friends, I am implementing a protocol on top of 'asyncore.dispatcher' to send streaming multimedia data over TCP socket. However, I found that the throughput of my current implementation is surprisingly low. Below is a snippet of my code with a note that: the packet sent over the socket is of variable length, of which the first a couple bytes indicates the length of the packet. I implemented a 'var_str_to_int' function to get the...
0
1304
by: Ben | last post by:
I modified the logmonitor sdk example so it would work over a network. It works great when the client and server are running on the same PC and have administrator privileges. So I have two problems: 1) I cannot run the client without administrator privileges. If I try I get the following message: Unhandled Exception: System.Security.SecurityException: Requested registry access is not allowed. at...
10
4463
by: Clayton | last post by:
Hi all, I'm trying to develop a server that listens to incoming calls using the asycnhronous methods BeginAccept / EndAccept. I start the server (till this point it is ok) and few seconds later I stop it (with no clients connected). Once I press the stop button an ObjectDisposedException is fired. What is the reason for this? Is it because the thread is still running even after I closed the server socket? Here is the code:
0
3582
by: george585 | last post by:
Hello! I am new to network programming, and understand just basics. Using some sample code, and having read documentation, I managed to create a simple app in C# and VB.NET. The application is supposed to do the following: monitor ALL INCOMING TCP traffic on the local computer, and save certain parts of it as files - not log files though, but actual files that are sent to the computer as part of http or ftp. Basically if a user browse a page...
16
3848
by: =?iso-8859-1?q?|-|e|=5F|=5F_B0=DD?= | last post by:
hi all! I got a problem. I declared a SOCKET var in my C program but when i compiled the program it displayed like *--------------------------------------------------------------* *'SOCKET': illegal use of this type as an expression * * C:\..\..\..\include\winsock2.h: see declaration of 'SOCKET' * *--------------------------------------------------------------* What i wrote in my program is like this..:
0
8749
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8662
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9243
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
8956
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
7853
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
6585
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
4420
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2057
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.