Socket Programming Example

Introduction

A socket is a passageway between two computers. For a socket to work as required, both the client as well as the server-side should have access to each other’s IP address and TCP Port.

A sample Socket can be created as follows:

Socket socket = new Socket (“128.0.0.1”, 500)

Here “128.0.0.1” is the IP address of the localhost and 500 is the port number on which the application will run.

Example

This is a simple example of socket programming where a socket connection will be established between a client and a server. The client will keep reading the input from the user and sent it to the server until the ‘Stop’ word is printed.

Client Socket
import java.net.*;
import java.io.*;
public class Client
{
private Socket socket = null;
private DataInputStream  input   = null;
private DataOutputStream out     = null;
public Client(String address, int port)
{
try
{
socket = new Socket(address, port);
System.out.println("Connected");
input  = new DataInputStream(System.in);
out    = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
String line = "";
while (!line.equals("Over"))
{
try
{
line = input.readLine(); out.writeUTF(line);
} catch(IOException i)
{
System.out.println(i);
}
}
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
Server Socket
import java.net.*;
import java.io.*;
public class Server
{
private Socket          socket   = null;
private ServerSocket    server   = null;
private DataInputStream in       =  null;
public Server(int port)
{
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
in = new DataInputStream( new BufferedInputStream(socket.getInputStream()));
String line = "";
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
 }
}
System.out.println("Closing connection");
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.