![]() |
|
Python netwoking - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Python (https://sinister.li/Forum-Python) +--- Thread: Python netwoking (/Thread-Python-netwoking--3933) |
Python netwoking - ICE_ - 02-01-2013 [shadow=black]PYTHON NETWORKING TUTORIAL[/shadow]
[shadow=green]Imports Needed:[/shadow] socket [shadow=red]Objects Used:[/shadow]
[shadow=blue]Examples/explenations of networking:[/shadow] Code: s = socket.socket (socket_family, socket_type, protocol=0)To network in python we need to make initialize a socket variable, the above code does this and uses 3 separate variables to set up the socket. These variables are:
Sockets have methods for both the client and the server side of a program. Server commands: bind() - binds to an address listen() - sets up and starts a TCP listener accept() - allows clients to connect through TCP connections Client commands: connect() - connects to a server through a tcp connections General commands: recv() - receives TCP message send() - sends TCP message recvfrom() - receives UDP message sendto() - sends UDP message close() - closes socket gethostname() - returns the hostname an example of a server: Code: #!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 2223 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connectionan example of a client: Code: #!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 2223 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done[shadow=black]I HOPE THIS TUTORIAL HELPED YOU! KEEP AN EYE OUT FOR MY OTHER NETWORKING TUTORIALS FOR DIFFERENT LANGUAGES![/shadow] |