socket connection code example

Example 1: socket

import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

Example 2: python network programming

import socket               # 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

Example 3: socket only connection

import socket # client
a = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = 'host ip '
port = 'host port'
a.connect((host,port))

Example 4: socket only connection

import socket #server
a = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

host = 'host ip '

port = 'port'

a.bind((host,port))

a.listen(5)#5 is the no. of client at a time 

socketclient,address  = a.accept()

print('got a connetion from',address)