Showing posts with label network programming. Show all posts
Showing posts with label network programming. Show all posts

Sunday, January 2, 2011

Synchronous Cilent Server application in java

Client code

Client.java

This program creates a socket connection with the server running on port 9050 on localhost and gets the input stream from the socket by chaining the BufferedReader with the InputStreamReader.


package clientserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

 public static void main(String args[]) {

  try {
   Socket s = new Socket("127.0.0.1", 9050);

   InputStreamReader streamreader = new InputStreamReader(
     s.getInputStream());
   BufferedReader br = new BufferedReader(streamreader);

   String number = br.readLine();

   System.out.println("Today's number is " + number);
   br.close();

  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}



Server code

Server.java

This program makes a ServerSocket and waits for client Requests. When a client tries to connect the server creates a new socket in a random port(using accept() method), which knows about the ip address and the port number of the client and makes the connection to the client. Also here server uses PrintWriter to sned messages to client.


package mainserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {

 public static void main(String args[]) {

  try {
   ServerSocket serverSock = new ServerSocket(9050);

   while (true) {

    Socket sock = serverSock.accept();
    PrintWriter pw = new PrintWriter(sock.getOutputStream());
    String TodayNum = new Server().getNumber();
    pw.println(TodayNum);
    pw.close();
    System.out.println(TodayNum);

   }

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 public String getNumber() {

  Random rg = new Random();
  int num = rg.nextInt(100);
  String numb = Integer.toString(num);
  return numb;

 }

}



Output

Tuesday, December 21, 2010

Network multicasting with C#

What is multicasting?

IP multicasting allows an application to send a single packet to a selected subset of devices. The IP multicasting scheme uses a particular range of IP addresses to designate different multicast groups. Each multicast group consists of a group of devices listening to the same IP address. As packets are sent out destined for the multicast group address, each device listening to the address receives them. The IP address range 224.0.0.1 through 239.255.255.255 represents multicast groups


In C# the Socket class supports IP multicasting by using the SetSocketOption() method of the socket.

MultiRecv program

The MultiRecv program creates a UDP socket in the normal way, using the standard Socket class methods. After being added to the multicast group, the socket blocks on a ReceiveFrom() method call, waiting for data to arrive


MultiRecv.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MultiRecv
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);
   Console.WriteLine("Ready to receive…");
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
   EndPoint ep = (EndPoint)iep;
   sock.Bind(iep);
   sock.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,newMulticastOption(IPAddress.Parse("224.100.0.1")));
   byte[] data = new byte[1024];
   int recv = sock.ReceiveFrom(data, ref ep);
   string stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
   sock.Close();
  }
}


MultiSend program

MultiSend.cs program is created to send multicast packets across network boundaries. when the multicast packet is sent out, it has a TTL(Time To Live) value of 50, allowing it to traverse up to 50 hops before it is terminated. You can use the MultiRecv program to watch the multicast packet go out on the network.


MultiSend.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class NewMultiSend
{
  public static void Main()
  {
   Socket server = new Socket(AddressFamily.InterNetwork,
                 SocketType.Dgram, ProtocolType.Udp);
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
   IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
   server.Bind(iep);
   
   byte[] data = Encoding.ASCII.GetBytes("This is a test message");
   server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
               new MulticastOption(IPAddress.Parse("224.100.0.1")));
   server.SetSocketOption(SocketOptionLevel.IP,
   SocketOptionName.MulticastTimeToLive, 50);
   server.SendTo(data, iep2);
   server.Close();
  }
}

Thursday, December 16, 2010

Network Broadcasting with C# further

This post is related to the previously written post Network Broadcasting with C#.

Consider the Broadcst.cs and RecvBroadcst.cs programs which were provided in Network Broadcasting with C#. In this post those two programs have slightly modified to achieve a special target described in the next paragraph.

Suppose a peer to peer environment. When a peer connected with the network it continually listens to one specific port and as well sends a broadcasting message in every 5 seconds to the same specific port to inform it is connected. That broadcasting message will be listened through the modified RecvBroadcst.cs program and it will also store the ip of the sender in an Arraylist.Broadcast message is sent through modified Broadcst.cs program. Program.cs is used to run the two threads.


RecvBroadcst.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;

class RecvBroadcst
{
    public void init()
    {

        while (true)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            sock.Bind(iep);
            EndPoint ep = (EndPoint)iep;
            Console.WriteLine("Ready to receive…");
            byte[] data = new byte[1024];
            int recv = sock.ReceiveFrom(data, ref ep);
            string stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());

            string ip = ep.ToString();

            string[] array = ip.Split(':');

            ArrayList list = new ArrayList();

            Console.WriteLine("sender ip {0} is added to the table!", array[0]);

            list.Add(array[0]);

            sock.Close();

        }
    }
}

Broadcst.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class Broadcst
{
    public void init()
    {

        while (true)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                         ProtocolType.Udp);
            IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
            string hostname = Dns.GetHostName();
            byte[] data = Encoding.ASCII.GetBytes(hostname);
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            sock.SendTo(data, iep1);
                       
            sock.Close();
            Thread.Sleep(5000);
            
        }
    }
}



Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;


    public class Program
    {
        static void Main(string[] args)
        {
           
            Thread RecvBraodcast = new Thread(new RecvBroadcst().init);
            Thread Broadcst = new Thread(new Broadcst().init);

            RecvBraodcast.Start();
            Broadcst.Start();
      
            

        }
    }

           

           


Run these codes in visual studio.

output

Tuesday, December 14, 2010

Network Broadcasting with C#

What Is Broadcasting?

IP broadcasting is used by network devices to send a single packet of information that can be accessible by every device on the network. Because TCP communication requires that two devices have a dedicated connection, it is not possible to send broadcast messages in a strictly TCP environment. Instead, UDP packets must be used because that protocol has the capability of sending messages without a specific connection being defined.

Broadcst.cs

The Broadcst program creates two separate IPEndPoint objects, one using the IPAddress.Broadcast address and one using a local broadcast address 192.168.1.255. Next, the local hostname of the device is determined using the standard Dns GetHostName() method, and it is sent out in two separate broadcast messages.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Broadcst
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                ProtocolType.Udp);
   IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
   IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
   string hostname = Dns.GetHostName();
   byte[] data = Encoding.ASCII.GetBytes(hostname);
   sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);
   sock.SendTo(data, iep1);
   sock.SendTo(data, iep2);
   sock.Close();
  }
}


RecvBroadcst.cs

The RecvBroadcst program is a simple UDP program that creates a socket and binds it to all network interfaces on the device, using port 9050, the same port that the Broadcst program uses to send its broadcast messages. After binding the socket to the UDP port, the program attempts to receive two messages sent to the port and displays the message and the sending host address information.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class RecvBroadcst
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork,
           SocketType.Dgram, ProtocolType.Udp);
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
   sock.Bind(iep);
   EndPoint ep = (EndPoint)iep;
   Console.WriteLine("Ready to receive…");
   byte[] data = new byte[1024];
   int recv = sock.ReceiveFrom(data, ref ep);
   string stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
   data = new byte[1024];
   recv = sock.ReceiveFrom(data, ref ep);
   stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
   sock.Close();
  }
}


For compilation either can use visual studio or visual studio command prompt. Here have used visual studio command prompt. Open up two Visual Studio Command prompts, one for the RecvBroadcst.cs and other one for the Broadcst.cs

Compile and run:

Broadcst

csc Broadcst.cs
Broadcst.exe

RecvBroadcst

csc RecvBroadcst.cs
RecvBroadcst.exe

output

Monday, November 29, 2010

System.Net.Sockets.Socket Class

System.Net.Sockets.Socket Class provides the basic functionality of a socket application.

  • Some important properties of System.Net.Sockets.Socket

Property Description
AddressFamily Gets the address family of the socket-the value is from the Socket.AddressFamily enumeration
Available
Returns the amount of available data to read
Blocking
Gets or sets the value which indicates whether the socket is in blocking mode or not
Connected
Returns the value that informs whether the socket is still connected with the remote host
LocalEndPoint
Gets the local endpoint
ProtocolType
Get the protocol type of the socket
RemoteEndPoint
Gets the remote endpoint of a socket
SocketType
Gets the type of the socket

  • Some important methods of System.Net.Sockets.Socket

Method Description
Accept()
Creates a new socket to handle the incoming connection request.
Bind()
Associates a socket with the local endpoint for listening to incoming connections.
Close()
Forces the socket to close itself.
Connect()
Establishes a connection with the remote host.
GetSocketOption()
Returns the value of a SocketOption.
IOControl()
Sets low-level operating modes for the socket. This method provides low-level access to the underlying socket instance of the Socket class.
Listen()
Places the socket in listening mode. This method is exclusive to server applications.
Receive()
Receives data from a connected socket.
Poll()
Determines the status of the socket.
Select()
Checks the status of one or more sockets.
Send()
Sends data to the connected socket.
SetSocketOption()
Sets a SocketOption.
Shutdown()
Disables send and receive on a socket.

Saturday, November 27, 2010

Sockets

Sockets

  • Socket is one end of a two way communication link between two programs running on a network.
  • Data can be passed between different processes by connecting the two sockets together

Basic socket types

  • Stream Socket
    • Connection oriented sockets
    • Consists of a stream of bytes that can be bi-directional
    • Usage of stream sockets is a more reliable method than the usage of datagram sockets
  • Datagram sockets
    • AKA Connectionless sockets, no explicit connection is established
    • A message is sent to a specified socket and can be received appropriately from the specified socket
    • Usage of datagram sockets is reducing the overhead incurred by establishing an explicit connection

Row sockets

  • Generalized form of sockets called row sockets
  • Packet is passed directly to the application that needs it bypassing the mechanism by which the computer handles TCP/IP

Ports

  • Defined to solve the problem of communicating with multiple operations simultaneously

Sockets composed of
  • IP address of the machine
  • Port no used by TCP application

Socket numbers are unique across the entire internet as IP address is unique across the internet and the port no is unique on the individual machine. This enables process to communicate with another process across network based entirely on socket number.

Client Server applications uses sockets

  • Server waits for the connection from the client
  • Client initiates the connection with the server
  • Server should be already running before client tries to connect
  • Client must know the target address and the port no, tries to establish a connection with the server
  • Server accepts the connection
  • Server application creates a new socket to deal specifically with the connected client
  • Server and client communicate by reading from and writing to their respective sockets