Tuesday 6 August 2013

Java Networking


Java is notably known to have good network capabilities that make the java programming world fun especially when it comes to communication. Here is a sample program code to show Client-Server and Server-Client communications using java networking capabilities.

Here is the Client source code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.*;
import java.util.Scanner;

/*

 * A simple demonstration of setting up a Java network client.

 */

public class Client
{
    static Scanner scanner = new Scanner(System.in);
//    static ServerSocket server;
    static Socket sock;

    public static void main(String[] argv) {

        String server_name = "localhost";
        String client_msg = null;

        try {

            sock = new Socket(server_name, 14323);
            /* Finally, we can read and write on the socket. */           

            System.out.println(" *** Connecting to " +
                sock.getInetAddress().getHostName() + ":" +
                sock.getLocalPort()  + " ***\n");
            while(sock.isConnected())
            {
//                System.out.println(" *** Connected ***\n");
                System.out.print("Enter message:");
                client_msg = scanner.nextLine();
                //send message to server
                sendMessage(client_msg);
                // wait for server's message
               
                // display new message from server
                receiveMessage();
                // handle connections
                //                handle(sock);
            }
            /* . do the I/O here .. */
            if(!sock.isClosed())
            {
                sock.close( );
                System.out.println("\nSocket closed\n");
            }

        } catch (java.io.IOException e) {

            System.err.println("error connecting to " +

                server_name + ": " + e);

            return;
        }
    }

    protected static void sendMessage(String msg) throws IOException
    {
        if(msg == "" || msg == null)
            return; // exit method
        sock.getOutputStream().write(msg.getBytes());
        System.out.println("\nMessage sent.");
    }

    protected static void receiveMessage() throws IOException
    {
        String recvmsg = "";
        int size = 256;
        byte[] buff = new byte[size];
        sock.getInputStream().read(buff);
        for(int i = 0; i < buff.length; i++)
        {
            if(buff[i] != buff[255])
                recvmsg += (char)buff[i];
        }
        System.out.println("\nServer: " + recvmsg);
    }

}


Here is the Server source code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**

 * Listen -- make a ServerSocket and wait for connections.

 */

public class Server {

    /** The TCP port for the service. */

    public static final short PORT = 14323;

    protected static ServerSocket sock;
    protected static Socket clientSock;
    protected static Scanner scanner;

    public static void main(String[] args) throws IOException
    {
        scanner = new Scanner(System.in);
        String servermsg;
        try {
            sock = new ServerSocket(PORT);

            System.out.println("\nListening on port " +
                    sock.getLocalPort());
                   
            // receive first message
            clientSock = sock.accept();
            while ((clientSock.isConnected()))
            {
//                System.out.println("Accepting from client " +
//                      clientSock.getInetAddress().getHostName() +
//                      ":" + clientSock.getLocalPort() + "\n");
                // wait for client's message first
               
                // display new client's message
                receiveMessage();
                // get server's message from standard input
                System.out.print("Enter message: ");
                servermsg = scanner.nextLine();
                // send server's message
                sendMessage(servermsg);               
               
            }
        }
        catch (IOException e)
        {
            System.err.println(e);
        }
        finally
        {
            sock.close();
            clientSock.close();
        }
    }  

    static void receiveMessage() throws IOException
    {
        int size = 256;
        byte[] recvbuff = new byte[size];
        clientSock.getInputStream().read(recvbuff);
        System.out.print("Client: ");
        for(int i = 0; i < recvbuff.length; i++)
        {
            if(recvbuff[i] != recvbuff[255])
                System.out.print("" + (char)recvbuff[i]);
        }
        System.out.println();
    }

    static void sendMessage(String msg) throws IOException
    {
        if(msg == "" || msg == null)
            return; // exit method
        int size = msg.getBytes().length;
        byte[] sendbuff = new byte[size];
        sendbuff = msg.getBytes();
        clientSock.getOutputStream().write(sendbuff);
        System.out.println("\nMessage sent.\n");
    }  

}



Here is the impressive output I heard you should have something similar on windows.




No comments:

Post a Comment