banner



How To Send Data To Server Using Socket In Java

In this Java network programming tutorial, you will learn how to develop a socket server plan to implement fully functional network customer/server awarding. Yous will also larn how to create a multi-threaded server.

Commencement, let'south empathise near the workflow and the API.

1. ServerSocket API

The ServerSocket form is used to implement a server plan. Here are the typical steps involve in developing a server program:

1. Create a server socket and bind it to a specific port number

2. Listen for a connection from the customer and accept information technology. This results in a client socket is created for the connexion.

iii. Read data from the client via an InputStream obtained from the client socket.

four. Send data to the client via the customer socket's OutputStream.

5. Shut the connexion with the customer.

The steps iii and 4 can be repeated many times depending on the protocol agreed between the server and the client.

The steps 1 to 5 can be repeated for each new client. And each new connection should be handled by a separate thread.

Let'southward dive into each step in details.

Create a Server Socket:

Create a new object of the ServerSocket class past using one of the following constructors:

- ServerSocket(int port): creates a server socket that is bound to the specified port number. The maximum number of queued incoming connections is gear up to fifty (when the queue is total, new connections are refused).

- ServerSocket(int port, int excess): creates a server socket that is leap to the specified port number and with the maximum number of queued connections is specified by the backlogparameter.

- ServerSocket(int port, int backlog, InetAddress bindAddr): creates a server socket and binds information technology to the specified port number and a local IP address.

So when to use which?

Employ the first constructor for a minor number of queued connections (less than 50) and any local IP address bachelor.

Use the 2nd constructor if you want to explicitly specify the maximum number of queued requests.

And utilise the third constructor if y'all desire to explicitly specify a local IP address to exist leap (in instance the reckoner has multiple IP addresses).

And of course, the first constructor is preferred for simple usage. For example, the following line of code creates a server socket and binds it to the port number 6868:

ServerSocket serverSocket = new ServerSocket(6868);

Note that these constructors can throw IOException if an I/O error occurs when opening the socket, so you have to take hold of or re-throw it.

Listen for a connexion:

Once a ServerSocket instance is created, call accept() to commencement listening for incoming client requests:

Socket socket = serverSocket.take();

Annotation that the accept() method blocks the electric current thread until a connectedness is made. And the connection is represented by the returned Socket object.

Read data from the client:

In one case a Socket object is returned, you can apply its InputStream to read information sent from the customer like this:

InputStream input = socket.getInputStream();

The InputStream allows you to read data at low level: read to a byte array. So if y'all want to read the data at higher level, wrap it in an InputStreamReader to read data every bit characters:

InputStreamReader reader = new InputStreamReader(input); int graphic symbol = reader.read();	// reads a single character

You can besides wrap the InputStream in a BufferedReader to read information as String, for more convenient:

BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String line = reader.readLine();	// reads a line of text

Transport data to the client:

Utilize the OutputStream associated with the Socket to send data to the customer, for example:

OutputStream output = socket.getOutputStream();

As the OutputStream provides only depression-level methods (writing data as a byte assortment), you tin can wrap it in a PrintWriter to send information in text format, for example:

PrintWriter writer = new PrintWriter(output, true); writer.println("This is a message sent to the server");

The argument true indicates that the writer flushes the data later on each method phone call (auto flush).

Close the client connection:

Invoke the close() method on the client Socket to terminate the connectedness with the client:

socket.close();

This method also closes the socket's InputStream and OutputStream, and it tin can throw IOException if an I/O error occurs when closing the socket.

Nosotros recommend you to use the endeavor-with-resource construction so you lot don't have to write lawmaking to close the socket explicitly.

Of course the server is however running, for serving other clients.

Finish the server:

A server should be ever running, waiting for incoming requests from clients. In example the server must be stopped for some reasons, call the close() method on the ServerSocket instance:

serverSocket.close();

When the server is stopped, all currently continued clients will be disconnected.

The ServerSocket class also provides other methods which you lot can consult in its Javadoc hither.

Implement a multi-threaded server:

So basically, the workflow of a server program is something like this:

ServerSocket serverSocket = new ServerSocket(port);  while (truthful) { 	Socket socket = serverSocket.have(); 	 	// read data from the client 	// ship data to the customer }

The while(truthful) loop is used to allow the server to run forever, always waiting for connections from clients. However, there'south a problem: Once the get-go customer is connected, the server may non be able to handle subsequent clients if information technology is busily serving the outset customer.

Therefore, to solve this trouble, threads are used: each client socket is handled past a new thread. The server's principal thread is only responsible for listening and accepting new connections. Hence the workflow is updated to implement a multi-threaded server like this:

while (true) { 	Socket socket = serverSocket.accept(); 	 	// create a new thread to handle customer socket }

Y'all will understand clearly in the examples below.

2. Java Server Socket Example #1: Fourth dimension Server

The following program demonstrates how to implement a uncomplicated server that returns the electric current engagement time for every new client. Here's the code:

import java.io.*; import java.net.*; import java.util.Appointment;  /**  * This program demonstrates a elementary TCP/IP socket server.  *  * @author world wide web.codejava.net  */ public grade TimeServer {  	public static void primary(String[] args) { 		if (args.length < 1) return;  		int port = Integer.parseInt(args[0]);  		endeavor (ServerSocket serverSocket = new ServerSocket(port)) {  			System.out.println("Server is listening on port " + port);  			while (truthful) { 				Socket socket = serverSocket.accept();  				System.out.println("New client continued");  				OutputStream output = socket.getOutputStream(); 				PrintWriter writer = new PrintWriter(output, truthful);  				author.println(new Date().toString()); 			}  		} catch (IOException ex) { 			Organization.out.println("Server exception: " + ex.getMessage()); 			ex.printStackTrace(); 		} 	} }

You demand to specify a port number when running this server program, for example:

java TimeServer 6868

This makes the server listens for customer requests on the port number 6868. You would see the server's output:

Server is listening on port 6868

And the following lawmaking is for a client plan that but connects to the server and prints the data received, and then terminates:

import java.cyberspace.*; import java.io.*;  /**  * This program demonstrates a simple TCP/IP socket customer.  *  * @author world wide web.codejava.internet  */ public class TimeClient {  	public static void main(String[] args) { 		if (args.length < 2) return;  		String hostname = args[0]; 		int port = Integer.parseInt(args[one]);  		try (Socket socket = new Socket(hostname, port)) {  			InputStream input = socket.getInputStream(); 			BufferedReader reader = new BufferedReader(new InputStreamReader(input));  			String time = reader.readLine();  			System.out.println(time);   		} catch (UnknownHostException ex) {  			System.out.println("Server not found: " + ex.getMessage());  		} take hold of (IOException ex) {  			System.out.println("I/O error: " + ex.getMessage()); 		} 	} }

To run this client program, you accept to specify the hostname/IP address and port number of the server. If the customer is on the same figurer with the server, type the following command to run it:

java TimeClient localhost 6868

And then you see a new output in the server plan indicating that the customer is connected:

New client connected

And y'all should see the client'due south output:

Mon Nov xiii xi:00:31 ICT 2017

This is the date time data returned from the server. Then the customer terminates and the server is nevertheless running, waiting for new connections. It's that simple.

three. Java Socket Server Example #2: Reverse Server (single-threaded)

Next, let's see a more complex socket server example. The following server plan echoes annihilation sent from the client in reversed form (hence the proper noun ReverseServer). Here's the code:

import java.io.*; import java.net.*;  /**  * This plan demonstrates a simple TCP/IP socket server that echoes every  * bulletin from the client in reversed form.  * This server is single-threaded.  *  * @author www.codejava.net  */ public form ReverseServer {  	public static void main(String[] args) { 		if (args.length < 1) return;  		int port = Integer.parseInt(args[0]);  		try (ServerSocket serverSocket = new ServerSocket(port)) {  			System.out.println("Server is listening on port " + port);  			while (truthful) { 				Socket socket = serverSocket.have(); 				System.out.println("New client continued");  				InputStream input = socket.getInputStream(); 				BufferedReader reader = new BufferedReader(new InputStreamReader(input));  				OutputStream output = socket.getOutputStream(); 				PrintWriter writer = new PrintWriter(output, true);   				String text;  				do { 					text = reader.readLine(); 					String reverseText = new StringBuilder(text).reverse().toString(); 					writer.println("Server: " + reverseText);  				} while (!text.equals("bye"));  				socket.close(); 			}  		} catch (IOException ex) { 			System.out.println("Server exception: " + ex.getMessage()); 			ex.printStackTrace(); 		} 	} }

Every bit you lot tin meet, the server continues serving the client until information technology says 'bye'. Run this server program using the post-obit command:

java ReverseServer 9090

The server is up and running, waiting for incoming requests from clients:

Server is listening on port 9090

Now, let's create a client program. The post-obit programme connects to the server, reads input from the user and prints the response from the server. Hither'due south the lawmaking:

import java.cyberspace.*; import coffee.io.*;  /**  * This program demonstrates a simple TCP/IP socket client that reads input  * from the user and prints echoed message from the server.  *  * @author www.codejava.net  */ public class ReverseClient {  	public static void main(String[] args) { 		if (args.length < 2) return;  		String hostname = args[0]; 		int port = Integer.parseInt(args[1]);  		endeavor (Socket socket = new Socket(hostname, port)) {  			OutputStream output = socket.getOutputStream(); 			PrintWriter writer = new PrintWriter(output, true);  			Console console = System.console(); 			Cord text;  			do { 				text = console.readLine("Enter text: ");  				author.println(text);  				InputStream input = socket.getInputStream(); 				BufferedReader reader = new BufferedReader(new InputStreamReader(input));  				String time = reader.readLine();  				System.out.println(time);  			} while (!text.equals("bye"));  			socket.close();  		} catch (UnknownHostException ex) {  			System.out.println("Server not found: " + ex.getMessage());  		} catch (IOException ex) {  			Organization.out.println("I/O error: " + ex.getMessage()); 		} 	} }

As y'all can see, this client programme is running until the user types 'adieu'. Run it using the following control:

java ReverseClient localhost 9090

Then it asks you lot to enter some text:

Enter text:_

Type something, say 'Howdy' and you lot should see the server's response similar this:

Enter text: Hullo Server: olleH Enter text:_

Y'all see the server responds 'Server: olleH' in which 'olledH' is the reversed form of 'How-do-you-do'. The text 'Server:' is added to clearly separate client's message and server'south bulletin. The client programme is still running, asking input and printing server's response until you type 'bye' to terminate it.

Keep this offset client program running, and beginning a new one. In the 2d client programme, you volition see it asks for input and then hangs forever. Why?

It's because the server is single-threaded, and while it is busily serving the first client, subsequent clients are block.

Allow's see how to solve this trouble in the next example.

4. Java Socket Server Example #3: Reverse Server (multi-threaded)

Modify the server'south code to handle each socket client in a new thread like this:

import java.io.*; import java.net.*;  /**  * This program demonstrates a simple TCP/IP socket server that echoes every  * bulletin from the customer in reversed form.  * This server is multi-threaded.  *  * @writer www.codejava.net  */ public grade ReverseServer {  	public static void main(String[] args) { 		if (args.length < one) return;  		int port = Integer.parseInt(args[0]);  		try (ServerSocket serverSocket = new ServerSocket(port)) {  			Arrangement.out.println("Server is listening on port " + port);  			while (true) { 				Socket socket = serverSocket.accept(); 				System.out.println("New customer connected");  				new ServerThread(socket).commencement(); 			}  		} catch (IOException ex) { 			Organization.out.println("Server exception: " + ex.getMessage()); 			ex.printStackTrace(); 		} 	} }

You come across, the server creates a new ServerThread for every socket client:

while (true) { 	Socket socket = serverSocket.accept(); 	System.out.println("New client continued");  	new ServerThread(socket).start(); }

The ServerThread class is implemented as follows:

import java.io.*; import java.cyberspace.*;  /**  * This thread is responsible to handle client connectedness.  *  * @author www.codejava.net  */ public course ServerThread extends Thread { 	private Socket socket;  	public ServerThread(Socket socket) { 		this.socket = socket; 	}  	public void run() { 		try { 			InputStream input = socket.getInputStream(); 			BufferedReader reader = new BufferedReader(new InputStreamReader(input));  			OutputStream output = socket.getOutputStream(); 			PrintWriter author = new PrintWriter(output, true);   			String text;  			exercise { 				text = reader.readLine(); 				String reverseText = new StringBuilder(text).reverse().toString(); 				writer.println("Server: " + reverseText);  			} while (!text.equals("bye"));  			socket.close(); 		} take hold of (IOException ex) { 			Arrangement.out.println("Server exception: " + ex.getMessage()); 			ex.printStackTrace(); 		} 	} }

Equally y'all can encounter, we just motility the processing code to be executed into a separate thread, implemented in the run() method.

Now let run this new server program and run several client programs, you will run into the problem above has solved. All clients are running smoothly.

Permit experiment the examples in this lesson in different ways: run multiple clients, test on local computer, and test on different computers (the server runs on a machine and the client runs on another).

API Reference:

Socket Class Javadoc

ServerSocket Class Javadoc

Related Coffee Network Tutorials:

  • Java InetAddress Examples
  • Java Socket Client Examples (TCP/IP)
  • Coffee UDP Client Server Program Example

Other Java network tutorials:

  • How to use Java URLConnection and HttpURLConnection
  • Java URLConnection and HttpURLConnection Examples
  • Java HttpURLConnection to download file from an HTTP URL
  • Java HTTP utility course to ship Become/POST request
  • How to Create a Conversation Console Awarding in Java using Socket
  • Java upload files by sending multipart request programmatically

Most the Author:

Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Coffee in the time of Java i.four and has been falling in dear with Java since then. Brand friend with him on Facebook and scout his Java videos you lot YouTube.

Add comment

How To Send Data To Server Using Socket In Java,

Source: https://www.codejava.net/java-se/networking/java-socket-server-examples-tcp-ip

Posted by: gloverfign1969.blogspot.com

0 Response to "How To Send Data To Server Using Socket In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel