Showing posts with label SOCKET PROGRAMMING. Show all posts
Showing posts with label SOCKET PROGRAMMING. Show all posts

Monday, 7 October 2013

Java client server Connection tutorial based on Screenshot [ part 2 ] , sending message from client to server

This tutorial is just  describing about the client server connection Establishment
.And passing a message to server from client
so what are the things we need
1.Linux OS/Win OS
2.TextEditor:
 gedit/Notepad
3.Terminal/Command prompt
4.java
Now what i'm using is linux mint,gedit,terminal,java

Step 1
-----------------------

first open gedit
type

this code and save as server1.java

    

import java.io.*;
import java.net.*;
public class server1
{
public static void main(String args[])throws IOException
{
ServerSocket servsocket=new ServerSocket(3000);
System.out.println(" server is waiting for client.......");
Socket s=servsocket.accept();
System.out.println(" Connection is success !!!!!");

DataInputStream ip;
ip=new DataInputStream (s.getInputStream());
System.out.println(" THE MESSAGE OF CLIENT IS :  "+ip.readUTF());
}
}
        
    

Step 2
-----------------
and type this code , then save it as client1.java
    

import java.io.*;
import java.net.*;
public class client1
{
public static void main(String args[])throws IOException
{

Socket clientsocket =new Socket("localhost",3000);

DataOutputStream op;
op=new DataOutputStream (clientsocket.getOutputStream());
op.writeUTF("** HAI I AM CLIENT **"); 
}
}
        
    



or you can type this code
for getting input from terminal

import java.io.*;
import java.net.*;
public class client1
{
public static void main(String args[])throws IOException
{
String str;
Socket clientsocket =new Socket("localhost",3000);

DataOutputStream op;
op=new DataOutputStream (clientsocket.getOutputStream());
System.out.println("Enter the message");

BufferedReader br;
br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
op.writeUTF(str);

}
}
 



Step 3
----------------
open terminal and type this code
javac Server1.java


java Server1



Now open another terminal
type this code
javac Client1.java


java Client


Monday, 2 September 2013

Socket programming using c++ (Connection Establishment)

Server Code
------------------------------------------------------------------------------


       
#include

#include

#include //inet_addr

//#include    //write

int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c;
    struct sockaddr_in server_addr , client;
     //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");
    //Prepare the socket address_in structure
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons( 9999 );
    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server_addr , sizeof(server_addr)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }
   puts("bind done");
    //Listen
    listen(socket_desc , 3);
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    //accept connection from an incoming client
    client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }
    puts("Connection accepted");
return 0;
}

      
 


**************************************************************************
Client Code
-------------------------------------------------------
       
#include    //printf,scanf
#include    //socket
#include //inet_addr
int main(int argc , char *argv[])
{
    int sock;
    struct sockaddr_in server_addr;
    //Create socket
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons( 9999 );
    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server_addr , sizeof(server_addr)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }
    puts("Connected\n");
return 0;
}
      
 
***************************************************************************
OUTPUT
------------------------
Open two terminal
First terminal
-------------------------
       

 gcc  server3.c && ./a.out

      
 

Second terminal
---------------------------------------
       

 gcc  client3.c && ./a.out

      
 










Socket programming using java ,Netbeans



Create serverForm


Name it "Formserver"
click finish


Now we get beutiful jframe form :-)

add a button from palette by "clicking and dragging"


Now name button to "start server"


By Right click on button->Edit text->


Now we can change the variable of button->"btnStart"


then click ok

                                  Goto formserver->source code section->
type


       
    ServerSocket server=null;
    Socket Client=null;
    DataOutputStream dos=null;
    DataInputStream dis=null;
       
 


Now got design section->Right click on button
select "action performed"
or double click on the button

Now we get coding section on button
type this code
To recover error just click that "error bulb"
it give suggestion to put try catch block so click that
 Now error dissappeared :-)
       
            try {
                server=new ServerSocket(9999);
                Client =server.accept();
                JOptionPane.showMessageDialog(null, "server accepted client request");
                dos=new DataOutputStream(Client.getOutputStream());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Client is not available");
        }
       
 

Now goto project explorer

Now goto project explorer
Add button change variable name to "btnconnect" change edit text to "connect"

Now goto Form client source code window type this
or copy paste this
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
  Socket server=null;
                                              DataOutputStream dos=null;
                                          DataInputStream dis=null;

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'""""


Now Double click on Connect button
copy paste this
       
        try {
            server=new Socket("localhost", 9999);
            JOptionPane.showMessageDialog(null, "Server connected");
            dis=new DataInputStream(server.getInputStream());
        } catch (UnknownHostException ex) {
             JOptionPane.showMessageDialog(null, "Connection failed :-( ");
        } catch (IOException ex) {
              JOptionPane.showMessageDialog(null, "Connection failed :-( ");
        }
       
 

""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""



Now add one more button(edit text:send,variable name:btnsend) by draggging to Formserver.java
add textfield(variable name:txtmsgsend





double click on send button

type this
or copy paste


""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
       
       try {
            String messg=txtmsgsend.getText();
            dos.writeUTF(messg);
        } catch (IOException ex) {
            Logger.getLogger(Formserver.class.getName()).log(Level.SEVERE, null, ex);
        }
       
 

Now goto Formserver.java

Now add one more button(edit text:Recieve,variable name:btnrecieve) by draggging to Formserver.java
add textfield(variable name:txtmsgrec)
Double click on Recieve button copy paste this code
       
           try {
            String msg=dis.readUTF();
            txtmsgrec.setText(msg);
         } catch (IOException ex) {
            Logger.getLogger(Formclient.class.getName()).log(Level.SEVERE, null, ex);
        }
       
 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Now you can see full code and Design of the forms below

Formserver Code
-----------
       
        import java.io.DataInputStream;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Formserver extends javax.swing.JFrame {
    ServerSocket server=null;
    Socket Client=null;
    DataOutputStream dos=null;
    DataInputStream dis=null;
    public Formserver() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // 
    private void initComponents() {
        btnStart = new javax.swing.JButton();
        btnSend = new javax.swing.JButton();
        txtmsgsend = new javax.swing.JTextField();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        btnStart.setText("Start Server");
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });
        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });
        txtmsgsend.setText(" ");
        txtmsgsend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtmsgsendActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(btnStart)
                .addContainerGap(279, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(91, 91, 91)
                .addComponent(txtmsgsend, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSend)
                .addGap(133, 133, 133))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(btnStart)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSend)
                    .addComponent(txtmsgsend, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(96, 96, 96))
        );
        pack();
    }// 
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
        try {
               server=new ServerSocket(9999);
                Client =server.accept();
                JOptionPane.showMessageDialog(null, "server accepted client request");
                dos=new DataOutputStream(Client.getOutputStream());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Client is not available");
        }
}
private void txtmsgsendActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String messg=txtmsgsend.getText();
            dos.writeUTF(messg);
        } catch (IOException ex) {
            Logger.getLogger(Formserver.class.getName()).log(Level.SEVERE, null, ex);
        }
}
        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Formserver().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnSend;
    private javax.swing.JButton btnStart;
    private javax.swing.JTextField txtmsgsend;
    // End of variables declaration
}
       
 


Formclient Code
       
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Formclient extends javax.swing.JFrame {
    Socket server=null;
    DataOutputStream dos=null;
    DataInputStream dis=null;
    public Formclient() {
    initComponents();
    }
    @SuppressWarnings("unchecked")
    // 
    private void initComponents() {
        btnConnect = new javax.swing.JButton();
        btnRecieve = new javax.swing.JButton();
        txtmsgrec = new javax.swing.JTextField();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        btnConnect.setText("Connect");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });
        btnRecieve.setText("Recieve");
        btnRecieve.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRecieveActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtmsgrec, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnRecieve))
                    .addComponent(btnConnect))
                .addContainerGap(120, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(50, 50, 50)
                        .addComponent(btnConnect))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(137, 137, 137)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtmsgrec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnRecieve))))
               .addContainerGap(140, Short.MAX_VALUE))
        );
        pack();
    }// 
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            server=new Socket("localhost", 9999);
            JOptionPane.showMessageDialog(null, "Server connected");
            dis=new DataInputStream(server.getInputStream());
        } catch (UnknownHostException ex) {
             JOptionPane.showMessageDialog(null, "Connection failed :-( ");
        } catch (IOException ex) {
              JOptionPane.showMessageDialog(null, "Connection failed :-( ");
        }
}
private void btnRecieveActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String msg=dis.readUTF();
            txtmsgrec.setText(msg);
        } catch (IOException ex) {
            Logger.getLogger(Formclient.class.getName()).log(Level.SEVERE, null, ex);
        }
}
    public static void main(String args[]) {
             //
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
        */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Formclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Formclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Formclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
           java.util.logging.Logger.getLogger(Formclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       }
        //
             java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Formclient().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnConnect;
    private javax.swing.JButton btnRecieve;
    private javax.swing.JTextField txtmsgrec;
    // End of variables declaration
}
       
 

Sunday, 1 September 2013

simple Java client server Connection tutorial based on Screenshot [ part 1 ]

This tutorial is just describing about the client server connection Establishment
so what are the things we need
1.Linux OS/Win OS
2.TextEditor:
 gedit/Notepad
3.Terminal/Command prompt
4.java
Now what i'm using is linux mint,gedit,terminal,java

Step 1
-----------------------

first open gedit






Step 2

Now copy paste this
       
    import java.io.*;
    import java.net.*;
    public class Client {
    public static void main(String []args) throws IOException{
    Socket sckt=new Socket("localhost",3000);
    }}
       
 

and save it Client.java in "/Documents" folder



Now open New file
copy paste
       
import java.io.*;
import java.net.*;
public class Server{
public static void main (String args[]) throws IOException
{
ServerSocket sc=new ServerSocket(3000);
System.out.println("waiting for client");
Socket clntS=sc.accept();
System.out.println("client conneted");
}
}
       
 

and save it Server.java in "/Documents " folder



this program runs with same computer i.e
server and client is in a computer itself  

  ***************************************************************************
open two terminal



type in first terminal
       

cd ~/Documents/

javac Server.java
 
      
 

//for compile java class
       

java Server
 
      
 

type in second terminal
       

cd ~/Documents
javac Client.java

      
 
//for compile java file
       

java Client

      
 





RUN Server.java




RUN Client.java

So how to connect two computers?
--------------------------------------------------------------
Here we put localhost ,which is the address of server
if we want connect two computer
within same network then
 put ip address
that is,
for example
-----------------------
our Hostel is networked
so my ip address is 192.168.1.15
Now you are confusing with ip address .
How to get ip address?
just type "ifconfig" in Terminal then enter




for windows type "ipconfig/all" then enter

and my neighbour is with 192.168.1.16
Consider ,i'm server and i execute "server.java"
then
my nieghbour will be client he execute "Client.java"
so my neighbour should write code
//Socket sckt=new Socket("192.168.1.15",3000);//



Facebook Twitter Delicious Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | coupon codes