ADVANCED PROGRAMMING PRACTICE ASSIGNMENT
1.Create Simple Client Server Application using TCP Socket where server issue a command which
will be executed at the client slide as a process of remote command execution
ANSWER:
Import Socket Library
To use a socket object in your program, start off by importing the socket library. No need to install
it with a package manager, it comes out of the box with Python.
import socket
Build Socket Objects
Now we can create socket objects in our code.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
This code creates a socket object that we are storing in the “sock” variable. The constructor is
provided a family and type parameter respectively. The family parameter is set to the default
value, which is the Address Format Internet.
The type parameter is set to Socket Stream, also the default which enables “sequenced, reliable,
two-way, connection-based byte streams” over TCP1.
Open and Close Connection
Once we have an initialized socket object, we can use some methods to open a connection, send
data, receive data, and finally close the connection.
## Connect to an IP with Port, could be a URL
sock.connect(('0.0.0.0', 8080))
## Send some data, this method can be called multiple times
sock.send("Twenty-five bytes to send")
## Receive up to 4096 bytes from a peer
sock.recv(4096)
## Close the socket connection, no more data transmission
sock.close()
Python Socket Client Server
Now that we know a few methods for transmitting bytes, let’s create a client and server program
with Python.
import socket
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(('0.0.0.0', 8080))
serv.listen(5)
while True:
conn, addr = serv.accept()
from_client = ''
while True:
data = conn.recv(4096)
if not data: break
from_client += data
print from_client
conn.send("I am SERVER<br>")
conn.close()
print 'client disconnected'
2. Write a Socket-based Python server program that responds to client messages as follows:
When it
receives a message from a client, it simply converts the message into all uppercase letters and
sends
back the same to the client. Write both client and server programs demonstrating this.
ANSWER:
// UDPServer.java: A simple UDP server program.
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String args[]){
DatagramSocket aSocket = null;
if (args.length < 1) {
System.out.println(“Usage: java UDPServer <Port Number>”);
System.exit(1);
}
try {
int socket_no = Integer.valueOf(args[0]).intValue();
aSocket = new DatagramSocket(socket_no);
byte[] buffer = new byte[1000];
while(true) {
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),
request.getLength(),request.getAddress(),
request.getPort());
aSocket.send(reply);
}
}
catch (SocketException e) {
System.out.println(“Socket: ” + e.getMessage());
}
catch (IOException e) {
System.out.println(“IO: ” + e.getMessage());
}
finally {
if (aSocket != null)
aSocket.close();
}
}
}
3.Write a ping-pong client and server application. When a client sends a ping message to the
server,
the server will respond with a pong message. Other messages sent by the client can be safely
dropped by the server.
ANSWER:
import socket
import threading
from utils import recv_variable_length,
send_variable_length
def main():
print "creating socket"
server_socket =
socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
print "binding socket to localhost"
server_socket.bind(("localhost", 8765))
print "listening"
server_socket.listen(5)
client_num = 0
while True:
#accept connections from outside
print "waiting for a client to
connect..."
(clientsocket, address) =
server_socket.accept()
#now do something with the clientsocket
#in this case, we'll pretend this is a
threaded server
t =
threading.Thread(target=handle_client,
args=(clientsocket, client_num))
t.run()
client_num += 1
def handle_client(socket, ident):
data = recv_variable_length(socket)
print "Recieved {}".format(data)
count = data.count("PING")
message = " ".join(["PONG"]*count)
send_variable_length(socket, message)
if __name__ == "__main__":
main()
4. Write a Socket based program server-client yo simulate a simple chat application where the
server is multithreaded which can serve for multiple clients at the same time.
ANSWERS:
# import socket programming library
import socket
# import thread module
from _thread import *
import threading
print_lock = threading.Lock()
# thread function
def threaded(c):
while True:
# data received from client
data = c.recv(1024)
if not data:
print('Bye')
# lock released on exit
print_lock.release()
break
# reverse the given string from client
data = data[::-1]
# send back reversed string to client
c.send(data)
# connection closed
c.close()
def Main():
host = ""
# reverse a port on your computer
# in our case it is 12345 but it
# can be anything
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded to port", port)
# put the socket into listening mode
s.listen(5)
print("socket is listening")
# a forever loop until client wants to exit
while True:
# establish connection with client
c, addr = s.accept()
# lock acquired by client
print_lock.acquire()
print('Connected to :', addr[0], ':', addr[1])
# Start a new thread and return its identifier
start_new_thread(threaded, (c,))
s.close()
if __name__ == '__main__':
Main()