Difference between revisions of "Socket Programming in Python"

From PeformIQ Upgrade
Jump to navigation Jump to search
Line 50: Line 50:


=Socket Comm Class=
=Socket Comm Class=
==Fixed Length==


<pre>
<pre>
Line 85: Line 87:
</pre>
</pre>


==Variable Length==
<pre>
</pre>


[[Category:Python]]
[[Category:Python]]
[[Category:Network]]
[[Category:Network]]
[[Category:Socket]]
[[Category:Socket]]

Revision as of 15:19, 31 August 2008

References

Examples

Client

#!/usr/bin/env python

# Create an INET, STREAMing socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#now connect to the web server on port 80 - the normal http port

s.connect(("www.performiq.com.au", 80))

Simple HTTP Server

#!/usr/bin/env python

# Create an INET, STREAMing socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a public host ip, and a well-known port

serversocket.bind((socket.gethostname(), 80))

# Become a server socket

serversocket.listen(5)

while True:
   # Accept connections from outside
   
   (clientsocket, address) = serversocket.accept()

   # Now do something with the clientsocket -
   # say, pretend this is a threaded server

   ct = client_thread(clientsocket)

   ct.run()

Socket Comm Class

Fixed Length

class socket_comm:
   '''demonstration class only 
      - coded for clarity, not efficiency
'''
   MSGLEN = 64

   def __init__(self, sock=None):
     if sock is None:
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   else:
      self.sock = sock

   def connect(host, port):
      self.sock.connect((host, port))

   def send(msg):
      totalsent = 0
      while totalsent < self.MSGLEN:
         sent = self.sock.send(msg[totalsent:])
         if sent == 0:
            raise RuntimeError, "Socket connection failed..."
         totalsent += sent

   def recv():
      msg = ''
      while len(msg) < self.MSGLEN:
         chunk = self.sock.recv(self.MSGLEN-len(msg))
         if chunk == '':
            raise RuntimeError, "Socket connection failed..."
         msg += chunk
         return msg

Variable Length