Minimal Server

import socket

s = socket.socket()

host = socket.gethostname()

port = 1234
s.bind((host, port))

s.listen(5)

while True:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for connecting')
    c.close()

Minimal Client

import socket

s = socket.socket()

host = socket.gethostname()
port = 1234

s.connect((hos

t, port))
print s.recv(1024)

These are the two examples given to me from the python book I'M currently reading in the network chapter. The problem is, I still have know idea how this would work. I don't image having the minimal server .py file floating around somewhere on a server would make it work. I have no idea how servers work but I'M expected to understand this from a book that teaches python. Please help, thanks.

It's pretty simple: a server is a program which runs on a machine and waits for clients to 'connect' to a port on this machine. A client is a program (usually running on another machine) which knows the name or the IP address of the server's machine and the port number where the server process is listening, and uses this information to connect to the server.

Once the server and the client are connected, the 2 programs start sending information to each other through a special software component called a socket. The information itself has the form of a stream of bytes.

There are numerous variations on this basic scheme: the client and the server must agree on the structure and the meaning of the character strings that they exchange. This is called a protocol and there are hundreds of protocols: http, ftp, ssh, etc. Second thing: to ease the programmer's perspective, the socket is often hidden in higher level software components. For example python has several modules to communicate on the web, which implement different forms of servers and clients.

When you can use a higher level component (for example the module paramiko to communicate with the ssh and sftp protocols), it's better to use them than to use raw sockets. With raw sockets, you may easily reinvent the wheel (and probably fail to do so) :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.