Register Login
Internet / AI Technology University (ITU/AITU)





|

Top Links: >> 80. Technology >> Internet Technology Summit Program >> 3. Threads and Network >> 3.2. Network
Current Topic: 3.2.3. Server Socket Example
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
Server Socket Example

Before we can send client request to a server, we need to make sure that server is running a ServerSocket object and is listening on the same port.

Here is a simple server demo:


package its.day15.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServerDemo {
/**
* This is a simple server socket demo
* The server socket will start at the assigned port number and will be waiting for requests from clients.
* Upon receiving the client request the server will create an internal socket to collaborate with the client socket
* The internal socket will open Input and Output streams.
* Then the method expects to receive a string from a client and return it back with addition " - from server"
* Then the server will close the streams and the internal socket
* It will continue waiting for more requests from the clients
*
* @param portNumber
*/
public void serverSocketService(int portNumber) {
ServerSocket server = null;
// register server socket on the portNumber
try {
server = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println("Server socket failure: " + e);
return;
}
// start a loop waiting for client requests
while (true) {
// make client request, socket and stream objects available for exception cases
String clientRequest = null;
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
// listen for a client request and accept the request from a
// client with creating a local socket
socket = server.accept();
// connect input/output streams to the socket
OutputStream outStream = socket.getOutputStream();
InputStream inStream = socket.getInputStream();
// transform into DataInputStream and DataOutputStream to use UTF strings
dos = new DataOutputStream(outStream);
dis = new DataInputStream(inStream);
// read the client request
clientRequest = new String(dis.readUTF());
// mirror this request into the response with a small addition
dos.writeUTF(clientRequest + " - from server!"); // demo response
// close the client connection, keep alive the server socket
socket.close();
} catch (Exception e) {
// exception with one client will not stop server from serving other clients
String response = "ERROR: Server socket failure: " + e + " on the clientRequest="+clientRequest;
if(dos != null) {
try {
dos.writeUTF(response);
dos.close();
dis.close();
socket.close();
} catch(Exception dosException) {
System.out.println(dosException);
}
}
System.out.println(response);
}
}
}
/**
* This test will start the server socket on localhost at the portNumber and be waiting for client requests
* @param args
*/
public static void main(String[] args) {
SimpleServerDemo server = new SimpleServerDemo();
server.serverSocketService(5555);
}
}
Was it clear so far? Highlight the text in question Or


Assignments:

1. Open Eclipse and under the package its.day15.sockets in the project week7.network ? create a NEW ? CLASS - SimpleServerDemo.
2. Type the source of this class provided above.
3. Get rid of red lines and do right mouse click on the source - Run ? As Java Application. Now you have server side ready for client requests!
4. Keep this class running and open the source of the ClientSocket.
5. Right mouse click on the source - Run ? As Java Application.
6. Your client sends a request to a server and you should see the response from the server in the Console as: Hello ? from server!
7. The server is still waiting for more requests.
8. Right mouse click on the client source and again - Run ? As Java Application.
9. You will see again the same response from the server.
10. Modify the main() method of the client. Instead of Hello say Prevet (Hello in Russian)
11. Right mouse click on the client source and again - Run ? As Java Application.
12. You will see a new response from the server.
13. Make sure to stop the server program before going to the next session.
14. Eclipse does not provide a simple way to stop a daemon programs. So, just kill Eclipse and start it again.
15. Now modify the serverSocketService method in the SimpleServerDemo class by providing a boolean stopTheProcess in the loop as it is shown below:

public void serverSocketService(int portNumber) {
boolean stopTheProcess = false; // THIS IS THE NEW LINE
ServerSocket server = null;
// register server socket on the portNumber
try {
server = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println("Server socket failure: " + e);
return;
}
// start a loop waiting for client requests
while (!stopTheProcess) { // THIS IS THE MODIFIED LINE
// make client request, socket and stream objects available for exception cases
String clientRequest = null;
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
try {
// listen for a client request and accept the request from a
// client with creating a local socket
socket = server.accept();
// connect input/output streams to the socket
OutputStream outStream = socket.getOutputStream();
InputStream inStream = socket.getInputStream();
// transform into DataInputStream and DataOutputStream to use UTF strings
dos = new DataOutputStream(outStream);
dis = new DataInputStream(inStream);
// read the client request
clientRequest = new String(dis.readUTF());
// mirror this request into the response with a small addition
dos.writeUTF(clientRequest + " - from server!"); // demo response
// close the client connection, keep alive the server socket
socket.close();
stopTheProcess = true; // THIS IS THE NEW LINE THAT WILL STOP THE SERVER DAEMON PROCESS
} catch (Exception e) {
// exception with one client will not stop server from serving other clients
String response = "ERROR: Server socket failure: " + e + " on the clientRequest="+clientRequest;
if(dos != null) {
try {
dos.writeUTF(response);
dos.close();
dis.close();
socket.close();
} catch(Exception dosException) {
System.out.println(dosException);
}
}
System.out.println(response);
stopTheProcess = true;
}
}
}


16. Get rid of red lines and do right mouse click on the source - Run ? As Java Application. Now you have server side ready for client requests!
17. Keep this class running and open the source of the ClientSocket.
18. Right mouse click on the source - Run ? As Java Application.
19. Your client sends a request to a server and you should see the response from the server in the Console.
20. The server will stop running after serving one client.
21. Enhance this example with more features in ClientSocket and ServerSocket programs by providing Business Requirements, Design Spec, and implementation Java programs. Compress together in 3.2.3.Sockets.Your.Name.zip and email to dean@ituniversity.us
22. Now you are ready to move to the next section.

We invite you to create your own questions and answers (QnA) to increase your rank and win the Top Creativity Prize!

Topic Graph | Check Your Progress | Propose QnA | Have a question or comments for open discussion?
<br/>package its.day15.sockets;
<br/>
<br/>import java.io.DataInputStream;
<br/>import java.io.DataOutputStream;
<br/>import java.io.IOException;
<br/>import java.io.InputStream;
<br/>import java.io.OutputStream;
<br/>import java.net.ServerSocket;
<br/>import java.net.Socket;
<br/>
<br/>public class SimpleServerDemo {
<br/>	/**
<br/>	 * This is a simple server socket demo
<br/>	 * The server socket will start at the assigned port number and will be waiting for requests from clients.
<br/>	 * Upon receiving the client request the server will create an internal socket to collaborate with the client socket
<br/>	 * The internal socket will open Input and Output streams.
<br/>	 * Then the method expects to receive a string from a client and return it back with addition " - from server"
<br/>	 * Then the server will close the streams and the internal socket
<br/>	 * It will continue waiting for more requests from the clients
<br/>	 * 
<br/>	 * @param portNumber
<br/>	 */
<br/>	public void serverSocketService(int portNumber) {
<br/>		ServerSocket server = null;
<br/>		// register server socket on the portNumber
<br/>		try {
<br/>			server = new ServerSocket(portNumber);
<br/>		} catch (IOException e) {
<br/>			System.out.println("Server socket failure: " + e);
<br/>			return;
<br/>		}
<br/>		// start a loop waiting for client requests
<br/>		while (true) {
<br/>			// make client request, socket and stream objects available for exception cases
<br/>			String clientRequest = null;
<br/>			Socket socket = null;
<br/>			DataOutputStream dos = null;
<br/>			DataInputStream dis = null;
<br/>			try {
<br/>				// listen for a client request and accept the request from a
<br/>				// client with creating a local socket
<br/>				socket = server.accept();
<br/>				// connect input/output streams to the socket
<br/>				OutputStream outStream = socket.getOutputStream();
<br/>				InputStream inStream = socket.getInputStream();
<br/>				// transform into DataInputStream and DataOutputStream to use UTF strings
<br/>				dos = new DataOutputStream(outStream);
<br/>				dis = new DataInputStream(inStream);				
<br/>				// read the client request
<br/>				clientRequest = new String(dis.readUTF());
<br/>				// mirror this request into the response with a small addition
<br/>				dos.writeUTF(clientRequest + " - from server!"); // demo response
<br/>				// close the client connection, keep alive the server socket
<br/>				socket.close();
<br/>			} catch (Exception e) {
<br/>				// exception with one client will not stop server from serving other clients
<br/>				String response = "ERROR: Server socket failure: " + e + " on the clientRequest="+clientRequest;
<br/>				if(dos != null) {
<br/>					try {
<br/>						dos.writeUTF(response);
<br/>						dos.close();
<br/>						dis.close();
<br/>						socket.close();
<br/>					} catch(Exception dosException) {
<br/>						System.out.println(dosException);
<br/>					}
<br/>				}
<br/>				System.out.println(response);
<br/>			}
<br/>		}
<br/>	}
<br/>	/**
<br/>	 * This test will start the server socket on localhost at the portNumber and be waiting for client requests
<br/>	 * @param args
<br/>	 */
<br/>	public static void main(String[] args) {
<br/>		SimpleServerDemo server = new SimpleServerDemo();
<br/>		server.serverSocketService(5555);
<br/>	}
<br/>}
<br/>






Was it clear so far? Highlight the text in question

Or



Assignments:

1. Open Eclipse and under the package its.day15.sockets in the project week7.network ? create a NEW ? CLASS - SimpleServerDemo.
2. Type the source of this class provided above.
3. Get rid of red lines and do right mouse click on the source - Run ? As Java Application. Now you have server side ready for client requests!
4. Keep this class running and open the source of the ClientSocket.
5. Right mouse click on the source - Run ? As Java Application.
6. Your client sends a request to a server and you should see the response from the server in the Console as: Hello ? from server!
7. The server is still waiting for more requests.
8. Right mouse click on the client source and again - Run ? As Java Application.
9. You will see again the same response from the server.
10. Modify the main() method of the client. Instead of Hello say Prevet (Hello in Russian)
11. Right mouse click on the client source and again - Run ? As Java Application.
12. You will see a new response from the server.
13. Make sure to stop the server program before going to the next session.
14. Eclipse does not provide a simple way to stop a daemon programs. So, just kill Eclipse and start it again.
15. Now modify the serverSocketService method in the SimpleServerDemo class by providing a boolean stopTheProcess in the loop as it is shown below:
<br/>	public void serverSocketService(int portNumber) {
<br/>		boolean stopTheProcess = false; // <font color=red>THIS IS THE NEW LINE</font>
<br/>		ServerSocket server = null;
<br/>		// register server socket on the portNumber
<br/>		try {
<br/>			server = new ServerSocket(portNumber);
<br/>		} catch (IOException e) {
<br/>			System.out.println("Server socket failure: " + e);
<br/>			return;
<br/>		}
<br/>		// start a loop waiting for client requests
<br/>		while (!stopTheProcess) { // <font color=red>THIS IS THE MODIFIED LINE</font>
<br/>			// make client request, socket and stream objects available for exception cases
<br/>			String clientRequest = null;
<br/>			Socket socket = null;
<br/>			DataOutputStream dos = null;
<br/>			DataInputStream dis = null;
<br/>			try {
<br/>				// listen for a client request and accept the request from a
<br/>				// client with creating a local socket
<br/>				socket = server.accept();
<br/>				// connect input/output streams to the socket
<br/>				OutputStream outStream = socket.getOutputStream();
<br/>				InputStream inStream = socket.getInputStream();
<br/>				// transform into DataInputStream and DataOutputStream to use UTF strings
<br/>				dos = new DataOutputStream(outStream);
<br/>				dis = new DataInputStream(inStream);				
<br/>				// read the client request
<br/>				clientRequest = new String(dis.readUTF());
<br/>				// mirror this request into the response with a small addition
<br/>				dos.writeUTF(clientRequest + " - from server!"); // demo response
<br/>				// close the client connection, keep alive the server socket
<br/>				socket.close();
<br/>				stopTheProcess = true; // <font color=red>THIS IS THE NEW LINE THAT WILL STOP THE SERVER DAEMON PROCESS</font>
<br/>			} catch (Exception e) {
<br/>				// exception with one client will not stop server from serving other clients
<br/>				String response = "ERROR: Server socket failure: " + e + " on the clientRequest="+clientRequest;
<br/>				if(dos != null) {
<br/>					try {
<br/>						dos.writeUTF(response);
<br/>						dos.close();
<br/>						dis.close();
<br/>						socket.close();
<br/>					} catch(Exception dosException) {
<br/>						System.out.println(dosException);
<br/>					}
<br/>				}
<br/>				System.out.println(response);
<br/>				stopTheProcess = true;
<br/>			}
<br/>		}
<br/>	}
<br/>


16. Get rid of red lines and do right mouse click on the source - Run ? As Java Application. Now you have server side ready for client requests!
17. Keep this class running and open the source of the ClientSocket.
18. Right mouse click on the source - Run ? As Java Application.
19. Your client sends a request to a server and you should see the response from the server in the Console.
20. The server will stop running after serving one client.
21. Enhance this example with more features in ClientSocket and ServerSocket programs by providing Business Requirements, Design Spec, and implementation Java programs. Compress together in 3.2.3.Sockets.Your.Name.zip and email to dean@ituniversity.us
22. Now you are ready to move to the next section.


We invite you to create your own questions and answers (QnA) to increase your rank and win the Top Creativity Prize!


Topic Graph | Check Your Progress | Propose QnA | Have a question or comments for open discussion?

Have a suggestion? - shoot an email
Looking for something special? - Talk to AI
Read: IT of the future: AI and Semantic Cloud Architecture | Fixing Education
Do you want to move from theory to practice and become a magician? Learn and work with us at Internet Technology University (ITU) - JavaSchool.com.

Technology that we offer and How this works: English | Spanish | Russian | French

Internet Technology University | JavaSchool.com | Copyrights © Since 1997 | All Rights Reserved
Patents: US10956676, US7032006, US7774751, US7966093, US8051026, US8863234
Including conversational semantic decision support systems (CSDS) and bringing us closer to The message from 2040
Privacy Policy