Explain A multi-threaded DateServe that listens on port 3000 and waits for requests from clients?

Answer

Here A multi-threaded DateServer that listens on port 3000 and waits for requests from clients. Whenever there is a request, the server replies by sending a Date object (over sockets) to the client as shown in Code Sample.

Code Sample: DateServer.java
import java.io.*;
import java.net.*;
import java.util.*;

public class DateServer 
extends Thread {

private ServerSocket dateServer;


public static void main
(String argv[]) throws Exception {
new DateServer();
}

public DateServer() throws Exception {
dateServer = new ServerSocket(3000);
System.out.println
("Server listening on port 3000.");
this.start();


public void run() {
while(true) {
try {
System.out.println("Waiting for connections.");
Socket client = dateServer.accept();
System.out.println("Accepted a connection
from: "+ client.getInetAddress());
Connect c = new Connect(client);
} catch(Exception e) {}
}
}
}

class Connect extends Thread {
private Socket client = null;
private ObjectInputStream ois = null;
private ObjectOutputStream oos = null;

public Connect() {}

public Connect(Socket clientSocket) {
client = clientSocket;
try {
ois = new ObjectInputStream
(client.getInputStream());
oos = new ObjectOutputStream
(client.getOutputStream());
} catch(Exception e1) {
try {
client.close();
}catch(Exception e) {
System.out.println(e.getMessage());
}
return;
}
this.start();
}


public void run() {
try {
oos.writeObject(new Date());
oos.flush();
// close streams and connections
ois.close();
oos.close();
client.close(); 
} catch(Exception e) {} 
}

All sockets Questions

Ask your interview questions on sockets

Write Your comment or Questions if you want the answers on sockets from sockets Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---