Unit-20 Networking (URL,SOCKETS (TCP/IP),DATAGRAMS) – I

TCP/Ip Client Sockets

Server Program

import java.net.*;
import java.lang.*;
import java.io.*;
public class Server
{
public static final int PORT=1025;
public static void main(String args[])
{
ServerSocket sersock=null;
Socket sock=null;
System.out.println("Wait!!");
try
{
sersock=new ServerSocket(PORT);
int number;
System.out.println("Server Started:"+sersock);
sock=sersock.accept();
System.out.println("Client Connected:"+sock);
DataInputStream ins=new DataInputStream(sock.getInputStream());
String clientMsg=new String(ins.readUTF());
System.out.println(clientMsg);
DataOutputStream dos=new DataOutputStream(sock.getOutputStream());
dos.writeUTF("Hello from server");
dos.close();
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket problem"+se.getMessage());
}
catch(Exception e)
{
System.out.println("Couldn't start"+e.getMessage());
}
System.out.println("Connection from:"+sock.getInetAddress());
}
} 

Client Program

import java.lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class Client
{
public static void main(String args[])
{
Socket sock=null;
DataInputStream dis=null;
DataOutputStream dos=null;
System.out.println("Trying to connect");
try
{
InetAddress ip=InetAddress.getByName("localhost");
sock=new Socket(ip,Server.PORT);
dos=new DataOutputStream(sock.getOutputStream());
dos.writeUTF("Hi from client");
DataInputStream is=new DataInputStream(sock.getInputStream());
String serverMsg=new String(is.readUTF());
System.out.println(serverMsg);
}
catch(SocketException e)
{
System.out.println("SocketException"+e);
}
catch(IOException e)
{
System.out.println("IOException"+e);
}
finally
{
try
{
sock.close();
}
catch(IOException ie)
{
System.out.println("Close Error:"+ie.getMessage());
}
}
}
}
Output : Server And Client