UNIXové sockety

Dva programy: server a klient. Server beží stále, klienti sa k nemu pripájajú.

   1 import socket
   2 import os
   3 
   4 serveraddress="/tmp/square_server"
   5 sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
   6 try:
   7         os.remove(serveraddress)
   8 except OSError:
   9         pass
  10 sock.bind(serveraddress)
  11 # 5 klientov moze cakat vo fronte
  12 sock.listen(5)
  13 while True:
  14         # sock_client vrati socket pripojeny na druhej strane na klienta
  15         (sock_client,address)=sock.accept()
  16         print "server: pripojenie od klienta"
  17         # Vybavujeme teraz jedneho klienta po druhom,
  18         # aby sme si zjednodusili zivot.
  19         # Klasika je teraz spravit fork() a vybavovat klientov
  20         # sucasne v child procesoch.
  21         input=sock_client.recv(1024)
  22         print "server: klient poslal", input
  23         output="%d\n" % (int(input)*int(input))
  24         print "server: vraciam", output
  25         sock_client.send(output)
  26         print "server: vybavene, zatvaram socket"
  27         sock_client.close()
unix_socket_server.py

   1 import socket
   2 import os
   3 import sys
   4 
   5 if len(sys.argv)<=1:
   6         print "Daj mi nejake cele cislo ako parameter"
   7         sys.exit(1)
   8 
   9 serveraddress="/tmp/square_server"
  10 sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
  11 sock.connect(serveraddress)
  12 
  13 print "klient: posielam servrovi", sys.argv[1]
  14 sock.send(sys.argv[1])
  15 
  16 ret=sock.recv(1024)
  17 print "klient: server povedal, ze", ret
  18 
  19 sock.close()
unix_socket_klient.py

PocitacoveSiete/Socket (last edited 2008-10-02 18:56:58 by GejzaJenca)