Networking/import socket

From Lofaro Lab Wiki
Revision as of 10:16, 27 November 2014 by Eeide (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

we used import socket for sending information over a network with a client and a server

server

the code for the server is

-host = '192.168.0.102' #gets comp ip address

-port = 20000 #random port this can be set to almost anything between 1023 and 6000 ish once you start a server if you need to restart it you will need to close that terminal and open a new one so the port will no longer be in use

-s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) this part is what tells the socket what kind of data we want to use AF_INET tells network/internet and sock_DGRAM tells it to use udp packets (these are somewhat unstable as they are not checked)

-s.bind((str(host), port)) #binds s to the server so it can be called

-data, addr = s.recvfrom(1024) this tells the program to wait till it gets a packet from the client the 1024 can be lowered but should be in base 2 if you leave it at 1024 it will be fine it just tells it to take data that is only 1024 or less

   host = '192.168.0.102'	
   port = 20000				
   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   s.bind((str(host), port))	

client this makes it so that if a port is taken it will try for a new port if one fails only works for client because server must be known

x=1                       #just a constant for the while loop
host = '192.168.0.111'    #this is the current computers IP
port = 21111              #this is just a random port number
server = ('192.168.0.102',20000)    #tells the computer where to listen and send the IP address in this one should match the computer above
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    #tells to use network/udp
while (x == 1):           
   try:
       print port
       s.bind((host, port))    #trys this port if it is taken then moves on to a new port
       x=0
   except IOError:
       port+=1
   else:
       port+=1