Network Programming
Network Programming
Network Programming
TCP: TCP stands for Transmission Control Protocol, which allows for
reliable communication between two applications. TCP is typically used over
the Internet Protocol, which is referred to as TCP/IP.
Socket Programming:
The
java.net.Socket
class
represents
a
socket,
and
the
java.net.ServerSocket class provides a mechanism for the server program to
listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two
computers using sockets:
The server invokes the accept() method of the ServerSocket class. This
method waits until a client connects to the server on the given port.
Socket Client:
GreetingClient is a client program that connects to a server by using a socket
and sends a greeting, and then waits for a response.
//Client Socket Program
import java.net.*;
import java.io.*;
import java.lang.*;
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();
}
}
}
Socket Server:
GreetingServer program is an example of a server application that uses the
Socket class to listen for clients on a port number specified by a commandline argument:
//Server Socket Program
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);
}
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
METHOD DESCRIPTION
The java.net.ServerSocket class is used by server applications to obtain a
port and listen for client requests
public int getLocalPort()- Returns the port that the server socket is
listening on. This method is useful if you passed in 0 as the port
number in a constructor and let the server find a port for you.
When the ServerSocket invokes accept(), the method does not return until a
client connects. After a client does connect, the ServerSocket creates a new
Socket on an unspecified port and returns a reference to this new Socket. A
TCP connection now exists between the client and server, and
communication can begin.