Friday, 9 December 2016

C#: Socket Programming

By using socket programming, you can establish a communication between two computers. By using C# Socket programming, you can establish communication between, two C# applications running on different machines.

In this post, I am going to explain two applications client, server. Server socket listens on particular port, client socket sends some data to the server. Server socket receives the data from client socket and prints to console.

You need to import following packages to work with sockets.

using System.Net;
using System.Net.Sockets;

Developing Server Socket
Socket class is used to define both server and client sockets. IN case of server socket, we bind to particular address, where as in client socket we connect to particular address.

Socket class provides following constructors.

Constructor
Description
Socket(AddressFamily, SocketType, ProtocolType)
Initializes a new instance of the Socket class using the specified address family, socket type and protocol.
Socket(SocketInformation)   
Initializes a new instance of the Socket class using the specified value returned from DuplicateAndClose.
Socket(SocketType, ProtocolType)     
Initializes a new instance of the Socket class using the specified socket type and protocol.
        
What is AddressFamily?
It specifies the addressing scheme of the Socket.
 For example,
 ‘AddressFamily.InterNetwork’ specifies Address for IP version 4.         
 ‘AddressFamily.InterNetworkV6’ specifies Address for IP version 6.

What is SocketType?
SocketType specifies the type of the socket, it can be Dgram, Raw, Rdm, Seqpacket, Stream, Unknown.

Go to following link for more information.

What is ProtocolType?
Specified the protocol used by socket. For example, it can be Tcp, Udp. Following link documents all the supported protocols.


Following step-by-step procedure explains how to create Server Socket?

Step 1: Define Socket object.

Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Step 2: Define IOEndPoint.

IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

Step 3: Bind serverSocket to serverEndPoint.
serverSocket.Bind(serverEndPoint);
serverSocket.Listen(100);

Step 4: Now you can accept the connections by calling Accept method. You can receive the data from client to byte array.

Socket accepted = serverSocket.Accept();
int bytesRead = accepted.Receive(buffer);

Following step-by-step procedure explains how to create client socket?

Step 1: Define client socket.
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Step 2: Connect to server end point.
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
clientSocket.Connect(serverEndPoint);

Step 3: Send data to server socket.
clientSocket.Send(bytes);

Step 4: Close the client socket, after you are done with the work.
clientSocket.Close();

Following are the complete working applications.
Server.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    public class ServerSocket
    {
        private int port;
        private Socket serverSocket;

        public ServerSocket(int port)
        {
            this.port = port;
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

            /* Associates a Socket with a local endpoint. */
            serverSocket.Bind(serverEndPoint);

            /*Places a Socket in a listening state.
             * The maximum length of the pending connections queue is 100 
             */
            serverSocket.Listen(100);
        }

        public void start()
        {
            Console.WriteLine("Starting the Server");

            /* Accept Connection Requests */
            Socket accepted = serverSocket.Accept();

            /* Get the size of the send buffer of the Socket. */
            int bufferSize = accepted.SendBufferSize;
            byte[] buffer = new byte[bufferSize];

            /* Receives data from a bound Socket into a receive buffer. It return the number of bytes received. */
            int bytesRead = accepted.Receive(buffer);

            byte[] formatted = new byte[bytesRead];

            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = buffer[i];
            }

            String receivedData = Encoding.Unicode.GetString(formatted);
            Console.WriteLine("Received Data " + receivedData);

            Console.WriteLine("Press some key to close");
            Console.Read();
        }
    }
    class Server
    {
        static void Main(string[] args)
        {
            ServerSocket server = new ServerSocket(1234);
            server.start();
        }
    }
}

Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace client
{
    public class ClientSocket{
        private Socket clientSocket;
        private int port;

        public ClientSocket(int port)
        {
            this.port = port;
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void start()
        {
            Console.WriteLine("Starting client socket");
            try
            {
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
                clientSocket.Connect(serverEndPoint);

                Console.WriteLine("Enter some data to send to server");

                String data = Console.ReadLine();

                byte[] bytes = Encoding.Unicode.GetBytes(data);

                clientSocket.Send(bytes);

                Console.WriteLine("Closing connection");

                clientSocket.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error while connectiong to server {}", e.Message );
            }
        }
    }

    class Client
    {
        static void Main(string[] args)
        {
            ClientSocket clientSocket = new ClientSocket(1234);
            clientSocket.start();

        }
    }
}

Following is my project structure.
Right click on server project. Go to Debug -> Start New Instance.

It opens command prompt and wait for some connection.

Now right click on client project, go to Debug -> Start New Instance.

It opens command prompt, type some data and press enter. Open the server command prompt, you can able to see the data that you entered in client end point.


Previous                                                 Next                                                 Home

SWT: Focus listeners

There are two types of focus listeners.
a.   FocusListener
b.   TraverseListener

Focus events occur, whenever a widget receives focus. A TraverseEvent is generated when a widget gains focus by means of traversal.

FocusListener
Focus events occur, whenever a widget receives focus. FocusListener interface provides following methods.

Method
Description
public void focusGained(FocusEvent e)
Sent when a control gets focus
public void focusLost(FocusEvent e)
Sent when a control loses focus
TraverseListener
The TraverseListener has one method, keyTraversed. This is called when the widget the handler is attached to is traversed by a traversal method, such as tabs or up and down arrows. 

TraverseListener interface provide following method.
Method
Description
public void keyTraversed(TraverseEvent e)
Sent when a traverse event occurs in a control.

Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test {

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static void addWidgetsToShell(Display display, Shell shell) {

  FocusListener focusListener = new FocusListener() {

   @Override
   public void focusGained(FocusEvent e) {
    System.out.println(e.widget + " got focus");
   }

   @Override
   public void focusLost(FocusEvent e) {
    System.out.println(e.widget + " lost focus");
   }

  };

  TraverseListener traverseListener = new TraverseListener() {

   @Override
   public void keyTraversed(TraverseEvent e) {
    System.out.println(e.widget + " was traversed");
   }

  };

  Button b1 = new Button(shell, SWT.PUSH);
  Button b2 = new Button(shell, SWT.PUSH);
  Button b3 = new Button(shell, SWT.PUSH);
  Button b4 = new Button(shell, SWT.PUSH);
  Button b5 = new Button(shell, SWT.PUSH);
  Button b6 = new Button(shell, SWT.PUSH);
  b1.setBounds(10, 10, 50, 50);
  b2.setBounds(100, 10, 50, 50);
  b3.setBounds(200, 10, 50, 50);
  b4.setBounds(10, 100, 50, 50);
  b5.setBounds(100, 100, 50, 50);
  b6.setBounds(200, 100, 50, 50);
  b1.setText("1");
  b2.setText("2");
  b3.setText("3");
  b4.setText("4");
  b5.setText("5");
  b6.setText("6");

  b1.addFocusListener(focusListener);
  b2.addFocusListener(focusListener);
  b3.addFocusListener(focusListener);
  b4.addFocusListener(focusListener);
  b5.addFocusListener(focusListener);
  b6.addFocusListener(focusListener);

  b1.addTraverseListener(traverseListener);
  b2.addTraverseListener(traverseListener);
  b3.addTraverseListener(traverseListener);
  b4.addTraverseListener(traverseListener);
  b5.addTraverseListener(traverseListener);
  b6.addTraverseListener(traverseListener);

 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}




Previous                                                 Next                                                 Home

Thursday, 8 December 2016

SWT: Text listeners

There are two types of text listeners.
a.   ModifyListener
b.   VerifyListener

ModifyListener
ModifyListener is used to get notifications, when the text has been changed. This method is called every time a character is modified. ModifyListener interface provides following methods.
Method
Description
public void modifyText(ModifyEvent e)
Sent when the text is modified.

VerifyListener
Sent when the text is about to be modified.  VerifyListener interface provides following methods.

Method
Description
public void verifyText(VerifyEvent e)
Sent when the text is about to be modified.

package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static void addWidgetsToShell(Display display, Shell shell) {

  Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
  text.setBounds(10, 10, 300, 100);

  text.addModifyListener(new ModifyListener() {

   @Override
   public void modifyText(ModifyEvent e) {
    System.out.println("Updated Text : " + text.getText());
   }

  });

  text.addVerifyListener(new VerifyListener() {

   @Override
   public void verifyText(VerifyEvent e) {
    System.out.println("Current Text : " + text.getText());
   }

  });

 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}

Run above application and try to type the string "Hello", you can able to see following messages in console.

Current Text :
Updated Text : H
Current Text : H
Updated Text : He
Current Text : He
Updated Text : Hel
Current Text : Hel
Updated Text : Hell
Current Text : Hell
Updated Text : Hello





Previous                                                 Next                                                 Home

Wednesday, 7 December 2016

SWT: Mouse listeners

There are 3 types of mouse listeners.
a.   MouseListener
b.   MouseMoveListener
c.    MouseTrackListener

MouseListener
MouseListener is used to track mouse click events. MouseListener interface provides following methods.

Method
Description
public void mouseDoubleClick(MouseEvent e)
Sent when mouse button is double clicked
public void mouseDown(MouseEvent e)
Sent when a mouse button is pressed.
public void mouseUp(MouseEvent e)
Sent when a mouse button is released.

Ex:
text.addMouseListener(new MouseListener() {

         @Override
         public void mouseDoubleClick(MouseEvent e) {
                 System.out.println("Mouse double clicked");
         }

         @Override
         public void mouseDown(MouseEvent e) {
                 System.out.println("Mouse pressed down");
         }

         @Override
         public void mouseUp(MouseEvent e) {
                 System.out.println("Mouse is released");
         }

});

MouseMoveListener
MouseMoveListener is used to keep track of mouse move events. MouseMoveListener has only one method mouseMove, used to track mouse move event.

Method
Description
public void mouseMove(MouseEvent e)
Sent when the mouse moves.

Ex:
text.addMouseMoveListener(new MouseMoveListener() {

         @Override
         public void mouseMove(MouseEvent e) {
                 System.out.println("Mouse moved");
         }

});

MouseTrackListener
MouseTrackListener is used to track mouse enter, exit and hover movements. MouseTrackListener interface provides following methods.

Method
Description
public void mouseEnter(MouseEvent e)
Sent when the mouse pointer passes into the area of the screen covered by a control.
public void mouseExit(MouseEvent e)
Sent when the mouse pointer passes out of the area of the screen covered by a control.
public void mouseHover(MouseEvent e)
Sent when the mouse pointer hovers over a control.

text.addMouseTrackListener(new MouseTrackListener() {

         @Override
         public void mouseEnter(MouseEvent e) {
                 System.out.println("Mouse Entered");

         }

         @Override
         public void mouseExit(MouseEvent e) {
                 System.out.println("Mouse Exited");

         }

         @Override
         public void mouseHover(MouseEvent e) {
                 System.out.println("Mouse Hover");

         }

});


Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static void addWidgetsToShell(Display display, Shell shell) {

  Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
  text.setBounds(10, 10, 300, 100);
  text.setEditable(false);
  text.setText("Click me to see the affect in console");

  text.addMouseListener(new MouseListener() {

   @Override
   public void mouseDoubleClick(MouseEvent e) {
    System.out.println("Mouse double clicked");
   }

   @Override
   public void mouseDown(MouseEvent e) {
    System.out.println("Mouse pressed down");
   }

   @Override
   public void mouseUp(MouseEvent e) {
    System.out.println("Mouse is released");
   }

  });

  text.addMouseMoveListener(new MouseMoveListener() {

   @Override
   public void mouseMove(MouseEvent e) {
    System.out.println("Mouse moved");
   }

  });

  text.addMouseTrackListener(new MouseTrackListener() {

   @Override
   public void mouseEnter(MouseEvent e) {
    System.out.println("Mouse Entered");

   }

   @Override
   public void mouseExit(MouseEvent e) {
    System.out.println("Mouse Exited");

   }

   @Override
   public void mouseHover(MouseEvent e) {
    System.out.println("Mouse Hover");

   }

  });
 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}



Previous                                                 Next                                                 Home