Socket Programming using python
Data Transport
There are two basic types of communications:
- Stream(TCP): Computers establish a connection with each other and read/write data in a continuous stream bytes like a file.This is the most common. It is also provide reliable ,oriented connection service, control(flow and congestion).
- Datagrams(UDP): Userdatagram protocol, Computer send discrete packets to each other.Each packet contains a collection of bytes,but each packet is separate and self-contained. It is faster than TCP.
SOCKETS
Combination of IP address and port number, a communication endpoint.
Socket Basic using python
To create a socket :
import socket
s=socket.socket(address_family,type)
- Address families :
socket.AF_INET6 Internet protocol (IPv6)
- Types:
s=socket(AF_INET, SOCK_STREAM)
for UDP connection
s=socket(AF_INET, SOCK_DGRAM)
- Server :
- Client:
TCP Server python code
#server_tcp.py
import os
from socket import *
host = ""
port = 13000
buf = 2048 #amount of data to receive
addr = (host, port)
T = socket(AF_INET, SOCK_STREAM)
T.bind(addr)
T.listen(1)
while True:
print "waiting for connection"
c,c_a=T.accept()
print "a request from \n: " ,c_a
while True:
data1=c.recv(buf)
print "receiving request message:\n",data1
if data1=="exit":
break;
c.close()
TCP Client python code
#client_tcp.py
import os
from socket import *
host = "127.0.0.1"
port = 13000
addr = (host, port)
T = socket(AF_INET, SOCK_STREAM)
print" connecting to server"
T.connect(addr)
while (1):
data=raw_input("send a request to server or type exit\n")
T.sendall(data)
if data=="exit":
break;
os._exit(0)
UDP Server Python Code
#server_udp.py
import os
from socket import *
host = ""
port = 13000
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
print "Waiting to receive messages..."
while True:
(data, addr) = UDPSock.recvfrom(buf)
print "A request from ip: \t" + addr[0]
print "Received message: " + data
if data == "exit":
break
UDPSock.close()
os._exit()
UDP client python code
#client_udp.py
import os
from socket import *
host = "127.0.0.1" # set to IP address of target computer
port = 13000
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = raw_input("send request to the server or type 'exit': ")
UDPSock.sendto(data, addr)
(data1, addr) = UDPSock.recvfrom(buf)
if data == "exit":
break
UDPSock.close()
os._exit(0)
Comments
Post a Comment