28.10.2021 Views

Python Tutorial ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Next, call the accept method of the returned object. This method waits until a client connects to the port you

specified and then returns a connection object that represents the connection to that client.

#!/usr/bin/python

import socket

# This is server.py file

# Import socket module

s = socket.socket()

# Create a socket object

host = socket.gethostname() # Get local machine name

port = 12345

# 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 connection

A Simple Client:

Now, we will write a very simple client program, which will open a connection to a given port 12345 and given

host. This is very simple to create a socket client using Python's socket module function.

The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a

socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.

The following code is a very simple client that connects to a given host and port, reads any available data from

the socket, and then exits:

#!/usr/bin/python

import socket

# This is client.py file

# Import socket module

s = socket.socket()

# Create a socket object

host = socket.gethostname() # Get local machine name

port = 12345

# Reserve a port for your service.

s.connect((host, port))

print s.recv(1024)

s.close

# Close the socket when done

Now, run this server.py in background and then run above client.py to see the result.

# Following would start a server in background.

$ python server.py &

# Once server is started run client as follows:

$ python client.py

This would produce the following result:

Got connection from ('127.0.0.1', 48437)

Thank you for connecting

Python Internet modules

A list of some important modules, which could be used in Python Network/Internet programming.

TUTORIALS POINT

Simply Easy Learning

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!