Tuesday, April 23, 2019


Implementation UDP Sockets

What is Sockets?

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.

Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest. Sockets have their own vocabulary −Sr.No. Term & Description

Overview of UDP based interaction between client and server

Domain

The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.





type

The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.



protocol

Typically zero, this may be used to identify a variant of a protocol within a domain and type.



hostname

The identifier of a network interface −

 A string, which can be a host name, a dotted-quad address, or an

IPV6 address in colon (and possibly dot) notation

 A string "<broadcast>", which specifies an INADDR_BROADCAST

address.

 A zero-length string, which specifies INADDR_ANY, or

 An Integer, interpreted as a binary address in host byte order.



5



port

Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

A Simple Server

To write Internet servers, we use the socket function available in socket  module to create a socket object. A socket object is then used to call other functions to setup a socket server.

A Simple Client

Let us write a very simple client program which opens 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.

Udp server.py

import socket



UDP_IP = "127.0.0.1"

UDP_PORT = 5005



sock = socket.socket(socket.AF_INET, # Internet

                     socket.SOCK_DGRAM) # UDP

sock.bind((UDP_IP, UDP_PORT))



while True:

    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes

    print ("received message:", data,"from", addr)



Udp Client.py

import socket
 
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
 
sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind(('', 54312))
sock.sendto(MESSAGE.encode('ascii'), (UDP_IP, UDP_PORT))
 
 



Output:

UDP server up and listening

Message from Client:b"Hello UDP Server"

Client IP Address:("127.0.0.1", 51696)



Message from Server b"Hello UDP Client"

Text Box: 18 April 2019

Implementation of Tcp socket





Client Side Programming

Establish a Socket Connection

To connect to other machine we need a socket connection. A socket connection means the two machines have information about each other’s network location (IP Address) and TCP port.The java.net.Socket class represents a Socket. To open a socket:

Socket socket = new Socket(“127.0.0.1”, 5000)

·         First argument – IP address of Server. ( 127.0.0.1  is the IP address of localhost, where code will run on single stand-alone machine).

·         Second argument – TCP Port. (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)


To communicate over a socket connection, streams are used to both input and output the data.

Closing the connection

The socket connection is closed explicitly once the message to server is sent.

In the program, Client keeps reading input from user and sends to the server until “Over” is typed.

Java Implementation

filter_none

edit

play_arrow

brightness_4

// A Java program for a Client
import java.net.*;
import java.io.*;
  
public class Client
{
    // initialize socket and input output streams
    private Socket socket            = null;
    private DataInputStream  input   = null;
    private DataOutputStream out     = null;
  
    // constructor to put ip address and port
    public Client(String address, int port)
    {
        // establish a connection
        try
        {
            socket = new Socket(address, port);
            System.out.println("Connected");
  
            // takes input from terminal
            input  = new DataInputStream(System.in);
  
            // sends output to the socket
            out    = new DataOutputStream(socket.getOutputStream());
        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
  
        // string to read message from input
        String line = "";
  
        // keep reading until "Over" is input
        while (!line.equals("Over"))
        {
            try
            {
                line = input.readLine();
                out.writeUTF(line);
            }
            catch(IOException i)
            {
                System.out.println(i);
            }
        }
  
        // close the connection
        try
        {
            input.close();
            out.close();
            socket.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
  
    public static void main(String args[])
    {
        Client client = new Client("127.0.0.1", 5000);
    }
}

Server Programming

Establish a Socket Connection

To write a server application two sockets are needed.

·         A ServerSocket which waits for the client requests (when a client makes a new Socket())

·         A plain old Socket socket to use for communication with the client.

Communication

getOutputStream() method is used to send the output through the socket.





Close the Connection

After finishing,  it is important to close the connection by closing the socket as well as input/output streams.



// A Java program for a Server
import java.net.*;
import java.io.*;
  
public class Server
{
    //initialize socket and input stream
    private Socket          socket   = null;
    private ServerSocket    server   = null;
    private DataInputStream in       =  null;
  
    // constructor with port
    public Server(int port)
    {
        // starts server and waits for a connection
        try
        {
            server = new ServerSocket(port);
            System.out.println("Server started");
  
            System.out.println("Waiting for a client ...");
  
            socket = server.accept();
            System.out.println("Client accepted");
  
            // takes input from the client socket
            in = new DataInputStream(
                new BufferedInputStream(socket.getInputStream()));
  
            String line = "";
  
            // reads message from client until "Over" is sent
            while (!line.equals("Over"))
            {
                try
                {
                    line = in.readUTF();
                    System.out.println(line);
  
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
            System.out.println("Closing connection");
  
            // close connection
            socket.close();
            in.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
  
    public static void main(String args[])
    {
        Server server = new Server(5000);
    }
}









1. First run the Server application as ,

$ java Server

Server started
Waiting for a client …

2. Then run the Client application on another terminal as,

$ java Client

It will show – Connected and the server accepts the client and shows,

Client accepted





3. Then you can start typing messages in the Client window. Here is a sample input to the Client

Hello

I made my first socket connection

Over

Which the Server simultaneously receives and shows,

Hello

I made my first socket connection

Over

Closing connection

Notice that sending “Over” closes the connection between the Client and the Server just like said before.