0
2.6kviews
Write a program for client-server application using Socket Programming(TCP)

Mumbai University > Computer Engineering > Sem 5 > Computer Networks

Marks: 10 Marks

Year: May 2016

1 Answer
0
16views

Socket Client Example:

The following Greeting Client is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

// File Name GreetingClient.java
import java.net.*;
import java.io.*;
publicclassGreetingClient
{
publicstaticvoid main(String[]args)
{
StringserverName=args[0];
int port =Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to "+serverName+
    " on port "+ port);
Socket client =newSocket(serverName, port);
System.out.println("Just connected to "
    +client.getRemoteSocketAddress());
OutputStreamoutToServer=client.getOutputStream();
DataOutputStreamout=newDataOutputStream(outToServer);
out.writeUTF("Hello from "
    +client.getLocalSocketAddress());
InputStreaminFromServer=client.getInputStream();
DataInputStreamin=
newDataInputStream(inFromServer);
System.out.println("Server says "+in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}}

Socket Server Example:

The following Greeting Server program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument.

// File Name GreetingServer.java
import java.net.*;
import java.io.*;
publicclassGreetingServerextendsThread
{
privateServerSocketserverSocket;

publicGreetingServer(int port)throwsIOException
{
serverSocket=newServerSocket(port);
serverSocket.setSoTimeout(10000);
}
publicvoid 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());
DataInputStreamin=
newDataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStreamout=
newDataOutputStream(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;
}
}publicstaticvoid main(String[]args)
{
int port =Integer.parseInt(args[0]);
try
{
Thread t =newGreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

Compile client and server and then start server as follows:

$ javaGreetingServer6066
    Waitingfor client on port 6066...

**Check client program as follows:**

    $ javaGreetingClientlocalhost6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
Please log in to add an answer.