Java socket to socket communication

Lesson 1: Socket Communications

Java Programming Language Basics, Part 1, finished with a simple network communications example using the Remote Method Invocation (RMI) application programming interface (API). The RMI example allows multiple client programs to communicate with the same server program without any explicit code to do this because the RMI API is built on sockets and threads.

This lesson presents a simple sockets-based program to introduce the concepts of sockets and multi-threaded programming. A multi-threaded program performs multiple tasks at one time such as fielding simultaneous requests from many client programs.

What are Sockets and Threads?

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program.

A server program typically provides resources to a network of client programs. Client programs send requests to the server program, and the server program responds to the request.

One way to handle requests from more than one client is to make the server program multi-threaded. A multi-threaded server creates a thread for each communication it accepts from a client. A thread is a sequence of instructions that run independently of the program and of any other threads.

Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients.

About the Examples

The examples for this lesson consist of two versions of the client and server program pair adapted from the FileIO.java application presented in Part 1, Lesson 6: File Access and Permissions.

Example 1 sets up a client and server communication between one server program and one client program. The server program is not multi-threaded and cannot handle requests from more than one client.

Читайте также:  Open source html css

Example 2 converts the server program to a multi-threaded version so it can handle requests from more than one client.

Example 1: Client-Side Behavior

The client program presents a simple user interface and prompts for text input. When you click the Click Me button, the text is sent to the server program. The client program expects an echo from the server and prints the echo it receives on its standard output.

Example 1: Server-Side Behavior

The server program presents a simple user interface, and when you click the Click Me button, the text received from the client is displayed. The server echoes the text it receives whether or not you click the Click Me button.

Example 1: Compile and Run

To run the example programs, start the server program first. If you do not, the client program cannot establish the socket connection. Here are the compiler and interpreter commands to compile and run the example.

 javac SocketServer.java javac SocketClient.java java SocketServer java SocketClient 

Example 1: Server-Side Program

The server program establishes a socket connection on Port 4321 in its listenSocket method. It reads data sent to it and sends that same data back to the server in its actionPerformed method.

listenSocket Method

The listenSocket method creates a ServerSocket object with the port number on which the server program is going to listen for client communications. The port number must be an available port, which means the number cannot be reserved or already in use. For example, Unix systems reserve ports 1 through 1023 for administrative functions leaving port numbers greater than 1024 available for use.

public void listenSocket() < try< server = new ServerSocket(4321); >catch (IOException e)

listenSocket Socket server.accept Socket

listenSocket BufferedReader client PrintWriter

Источник

Java Socket Programming — Socket Server, Client example

Java Socket Programming - Socket Server, Client example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Читайте также:  Триггер в python это

Welcome to Java Socket programming example. Every server is a program that runs on a specific system and listens on a specific port. Sockets are bound to the port numbers and when we run any server it just listens on the socket and waits for client requests. For example, tomcat server running on port 8080 waits for client requests and once it gets any client request, it responds to them.

Java Socket Programming

java socket, java socket programming, java socket example

A socket is one endpoint of a two-way communication link between two programs running on the network. The socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. In java socket programming example tutorial, we will learn how to write java socket server and java socket client program. We will also learn how server client program read and write data on the socket. java.net.Socket and java.net.ServerSocket are the java classes that implements Socket and Socket server.

Java Socket Server Example

package com.journaldev.socket; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ClassNotFoundException; import java.net.ServerSocket; import java.net.Socket; /** * This class implements java Socket server * @author pankaj * */ public class SocketServerExample < //static ServerSocket variable private static ServerSocket server; //socket server port on which it will listen private static int port = 9876; public static void main(String args[]) throws IOException, ClassNotFoundException< //create the socket server object server = new ServerSocket(port); //keep listens indefinitely until receives 'exit' call or program terminates while(true)< System.out.println("Waiting for the client request"); //creating socket and waiting for client connection Socket socket = server.accept(); //read from socket to ObjectInputStream object ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); //convert ObjectInputStream object to String String message = (String) ois.readObject(); System.out.println("Message Received: " + message); //create ObjectOutputStream object ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); //write object to Socket oos.writeObject("Hi Client "+message); //close resources ois.close(); oos.close(); socket.close(); //terminate the server if client sends exit request if(message.equalsIgnoreCase("exit")) break; >System.out.println("Shutting down Socket server!!"); //close the ServerSocket object server.close(); > > 

Java Socket Client

package com.journaldev.socket; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; /** * This class implements java socket client * @author pankaj * */ public class SocketClientExample < public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException< //get the localhost IP address, if server is running on some other IP, you need to use that InetAddress host = InetAddress.getLocalHost(); Socket socket = null; ObjectOutputStream oos = null; ObjectInputStream ois = null; for(int i=0; i<5;i++)< //establish socket connection to server socket = new Socket(host.getHostName(), 9876); //write to socket using ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); System.out.println("Sending request to Socket Server"); if(i==4)oos.writeObject("exit"); else oos.writeObject(""+i); //read the server response message ois = new ObjectInputStream(socket.getInputStream()); String message = (String) ois.readObject(); System.out.println("Message: " + message); //close resources ois.close(); oos.close(); Thread.sleep(100); >> > 

To test java socket programming of server-client communication, first we need to run SocketServerExample class. When you will run socket server, it will just print “Waiting for client request” and then wait for the client request. Now when you will run SocketClientExample class, it will send a request to java socket server and print the response message to console. Here is the output of java socket server SocketServerExample program.

Waiting for the client request Message Received: 0 Waiting for the client request Message Received: 1 Waiting for the client request Message Received: 2 Waiting for the client request Message Received: 3 Waiting for the client request Message Received: exit Shutting down Socket server!! 
Sending request to Socket Server Message: Hi Client 0 Sending request to Socket Server Message: Hi Client 1 Sending request to Socket Server Message: Hi Client 2 Sending request to Socket Server Message: Hi Client 3 Sending request to Socket Server Message: Hi Client exit 

That’s all for a quick roundup of Socket programming in java. I hope you can get started with java socket server and java socket client programming. Reference: Oracle Doc

Читайте также:  Docker обновить версию php

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью