FNL Socket
FNL Socket
FNL Socket
The server forms the listener socket while the client reaches out to
the server. Socket and Server Socket classes are used for connection-
oriented socket programming.
Now that you know, what is Socket in Java, let’s move further and
understand how does client communicates with the server and how
the server responds back.
Client-Side Programming
In the case of client-side programming, the client will first wait for
the server to start. Once the server is up and running, it will send the
requests to the server. After that, the client will wait for the response
from the server. So, this is the whole logic of client and server
communication. Now let’s understand the client-side and server-
side programming in detail.
1. Establish a Connection
2. Communication
import java.io.*;
class MyClient{
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
dout.close();
s.close();
}}
Now, let’s implement server-side programming and then arrive at
the output.
Server-Side Programming
Basically, the server will instantiate its object and wait for the client
request. Once the client sends the request, the server will
communicate back with the response.
After this, you need to communicate with the client with the
response.
Communication
import java.io.*;
class MyServer{
Socket s=ss.accept();
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
din.close();
s.close();
ss.close();
}}
After configuring both client and server end, you can execute the
server-side program first. After that, you need to run the client side
program and send the request. As soon as the request is sent from
the client end, the server will respond back. Below snapshot
represents the same.
1. When you run the server-side script, it will start and wait for the
client to get started.
2. Next, the client will get connected and inputs the request in the
form of a string.
3. When the client sends the request, the server will respond back.
That’s how you need to execute a socket program in Java. You can
also execute these programs on a terminal window or a command
prompt. But, as Eclipse is well advanced with its features, you can
simply execute both the programs on a console.