简体   繁体   中英

Sockets Python Connection

i am programing a client/server software in Python using sockets.

I have a question, specifically for the TCP/IP and Socket models:

I am using this example of code on my server side (server side program in Python):

import socket
# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Prevent from "address already in use"
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind the socket to port
server_address = ("localhost", 5000)
server.bind(server_address)

# Listen for connections
server.listen(5)

# Wait for on incomming connection
read = connection.recv(1024)
print "Received: ",read

Everything is fine, but i have some conceptual questions:

1) How is the best practice for enable this comunication?? Do I have to setup a heartbeat traffic for the TCP/IP between the CLIENT and SERVER programs?? I saw that even i leave the client program without traffic (idle) with the server, when i come back and send another message (a lot of minutes and minutes after the connection establishing) the messages stills go. Is it normal behavior?

2) The TCP/IP stack or even the "socket module" has any kind of TIMEOUT function?!?! Who can i control lost our "timed-out" connections in Python using the socket module??

Tks for all !

In TCP, heartbeats are not needed to keep the connection alive. Connections will live as long as both endpoints are still healthy.

However, a heartbeat can be useful to detect failures early. Otherwise, you'll only find out when you try to send data (or expect the other end to send data) whether the connection is still alive. In many cases, this is good enough. But for some (like an IRC application) you want to know soon after the client goes down, so you can notify others that they have been removed from the channel.

You might be able to use the SO_KEEPALIVE socket option to send heartbeat packets automatically, but I have no experience with it. This question may be helpful.

For timeouts, use the SO_RCVTIMEO and SO_SNDTIMEO socket options. See man 7 socket and the Python socket documentation for more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM