Reputation: 603
I've been messing around with Python sockets in hope of understanding how network programming is done better. Right now I'm trying to set up a client that connects to a server and can send it any number of messages before closing. I'm still not quite understanding everything and I can only get it to send one message. It's probably something obvious to someone experienced with socket programming. Could someone explain to me how to get it to send multiple messages? Maybe provide me a good source that explains how the connect, bind, close, recv, and all the main socket functions work? (Most the sources I find just tell me when to use them.)
Client
# !usr/bin/python
import socket
import sys
def main():
host = ""
port = 8934
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connect to server
s.connect((host,port))
while message != "/e":
#Send Data
message = raw_input("Send >> ")
try:
s.sendall(message)
except socket.error, msg:
print "ERROR %s"%(msg[1])
print "Failed to send."
s.close()
if __name__ == "__main__":
main()
Server
# !usr/bin/python
import socket
import sys
HOST = ""
PORT = 8934
s = socket.socket()
class BoServer:
def __init__(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
def bind(self):
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
def run(self):
while True:
s.listen(10)
print "Socket Listening"
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
income = conn.recv(4096)
if income != "":
print income
def main():
serv = BoServer()
serv.bind()
serv.run()
if __name__ == "__main__":
main()
Upvotes: 4
Views: 7689
Reputation: 43899
On your client side, you're closing the socket inside your while True:
loop, so you will not be able to transmit more messages on future iterations of the loop. If you intend to send each message on a different connection, then you will need to create the socket within the loop. If you intend to send multiple messages on the same connection, then you will need to move the close call outside the loop.
On the server side, you're running listen() once every iteration of the loop which is unnecessary: its purpose is to set the queue length for buffered incoming connections, so only needs to be called once. You are also only performing a single read from the socket before continuing to a second iteration of the loop where you accept another incoming connection.
Depending on how you want your server to behave, another potential problem is that you are only servicing a single incoming connection at a time. If you intend to deal with long running connections, then this could be a problem. To handle multiple connections at once, you'll probably want to either handle each connection on its own thread (e.g. using the ThreadingTCPServer
class from the SocketServer
standard library module), or use an asynchronous IO framework like Twisted.
Upvotes: 6