What are Sockets and Threads?

in #programming7 years ago

What are Sockets and Threads ?
A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs.The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program.
3.png
A server program typically provides resources to a network of client programs.Client programs send requests to the server program, and the server program responds to the request.
One way to handle requests from more than one client is to make the server program multi - threaded.A multi - threaded server creates a thread
for each communication it accepts from a client.A thread is a sequence of instructions that run independently of the program and of any other threads.
Using threads, a multi - threaded server program can accept a connection from a client, start a thread
for that communication, and
continue listening
for requests from other clients.
4.gif
// File Name GreetingClient.java
import java.net.;
import java.io.
;

public class GreetingClient {

public static void main(String[] args) {
    String serverName = args[0];
    int port = Integer.parseInt(args[1]);
    try {
        System.out.println("Connecting to " + serverName + " on port " + port);
        Socket client = new Socket(serverName, port);

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        OutputStream outToServer = client.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);

        out.writeUTF("Hello from " + client.getLocalSocketAddress());
        InputStream inFromServer = client.getInputStream();
        DataInputStream in = new DataInputStream(inFromServer);

        System.out.println("Server says " + in .readUTF());
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

// File Name GreetingServer.java
import java.net.;
import java.io.
;

public class GreetingServer extends Thread {
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {
    serverSocket = new ServerSocket(port);
    serverSocket.setSoTimeout(10000);
}

public void run() {
    while (true) {
        try {
            System.out.println("Waiting for client on port " +
                serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();

            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());

            System.out.println( in .readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();

        } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
}

public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);
    try {
        Thread t = new GreetingServer(port);
        t.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

An Overview of RMI Applications
RMI applications often comprise two separate programs, a server and a client.A typical server program creates some remote objects, makes references to these objects accessible, and waits
for clients to invoke methods on these objects.A typical client program obtains a remote reference to one or more remote objects on a server and then invokes methods on them.RMI provides the mechanism by which the server and the client communicate and pass information back and forth.Such an application is sometimes referred to as a distributed object application.
Distributed object applications need to do the following: •Locate remote objects.Applications can use various mechanisms to obtain references to remote objects.For example, an application can register its remote objects with RMI 's simple naming facility, the RMI registry. Alternatively, an application can pass and return remote object references as part of other remote invocations.•
Communicate
with remote objects.Details of communication between remote objects are handled by RMI.To the programmer, remote communication looks similar to regular Java method invocations.•Load class definitions
for objects that are passed around.Because RMI enables objects to be passed back and forth, it provides mechanisms
for loading an object 's class definitions as well as for transmitting an object'
s data.
The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a reference to a remote object.The server calls the registry to associate(or bind) a name with a remote object.The client looks up the remote object by its name in the server 's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing web server to load class definitions, from server to client and from client to server, for objects when needed.

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmiimplementation.*;

public class RMIServer {

public static void main(String[] args) {
    try {
        Registry reg = LocateRegistry.createRegistry(1099);
        RMIImplementation r = new RMIImplementation();
        ExtraImplementation i = new ExtraImplementation();
        reg.rebind("Calculator", r);
        reg.rebind("Extra", i);

        System.out.println("Server is running");

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

}

mport java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmi.CalculatorInterface;
import rmi.ExtraInterface;

public class RMIClient {

public static void main(String[] args) {
    try {
        Registry reg = LocateRegistry.getRegistry("127.0.0.1", 1099);
        CalculatorInterface r = (CalculatorInterface) reg.lookup("Calculator");
        System.out.println("1 + 1 = " + r.add(1, 1));
        System.out.println("1 + 1 = " + r.sub(0, 0));
        ExtraInterface ii = (ExtraInterface) reg.lookup("Extra");

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

}

}

import java.rmi.Remote;
import java.rmi.RemoteException;

/**

  • @author Venter.F
    */
    public interface ExtraInterface extends Remote {

    public int add1(int a, int b) throws RemoteException;
    public int sub2(int a, int b) throws RemoteException;

}
package rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface CalculatorInterface extends Remote {

public int add(int a, int b) throws RemoteException;
public int sub(int a, int b) throws RemoteException;

}

JDBC Batch
package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCBatchUpdateExample {

private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
private static final String DB_USER = "user";
private static final String DB_PASSWORD = "password";

public static void main(String[] argv) {

    try {

        batchInsertRecordsIntoTable();

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    }

}

private static void batchInsertRecordsIntoTable() throws SQLException {

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String insertTableSQL = "INSERT INTO DBUSER" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES" + "(?,?,?,?)";

    try {
        dbConnection = getDBConnection();
        preparedStatement = dbConnection.prepareStatement(insertTableSQL);

        dbConnection.setAutoCommit(false);

        preparedStatement.setInt(1, 101);
        preparedStatement.setString(2, "mkyong101");
        preparedStatement.setString(3, "system");
        preparedStatement.setTimestamp(4, getCurrentTimeStamp());
        preparedStatement.addBatch();

        preparedStatement.setInt(1, 102);
        preparedStatement.setString(2, "mkyong102");
        preparedStatement.setString(3, "system");
        preparedStatement.setTimestamp(4, getCurrentTimeStamp());
        preparedStatement.addBatch();

        preparedStatement.setInt(1, 103);
        preparedStatement.setString(2, "mkyong103");
        preparedStatement.setString(3, "system");
        preparedStatement.setTimestamp(4, getCurrentTimeStamp());
        preparedStatement.addBatch();

        preparedStatement.executeBatch();

        dbConnection.commit();

        System.out.println("Record is inserted into DBUSER table!");

    } catch (SQLException e) {

        System.out.println(e.getMessage());
        dbConnection.rollback();

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

}

private static Connection getDBConnection() {

    Connection dbConnection = null;

    try {

        Class.forName(DB_DRIVER);

    } catch (ClassNotFoundException e) {

        System.out.println(e.getMessage());

    }

    try {

        dbConnection = DriverManager.getConnection(
            DB_CONNECTION, DB_USER, DB_PASSWORD);
        return dbConnection;

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    }

    return dbConnection;

}

private static java.sql.Timestamp getCurrentTimeStamp() {

    java.util.Date today = new java.util.Date();
    return new java.sql.Timestamp(today.getTime());

}

}

Sort:  

Awesome post! Some suggestions: the formatting is a little off -- not a huge deal, but I figured I'd mention it. It'd also be nice if you broke the code down a bit more. I think it can be overwhelming to people who either don't know Java or are unfamiliar with the material you're reviewing.

Nice post, welcome to the programming section :)

Coin Marketplace

STEEM 0.17
TRX 0.13
JST 0.027
BTC 58430.35
ETH 2623.36
USDT 1.00
SBD 2.42