Java Socket Programming
Java Socket Programming
Method Description
ServerSocket class
The ServerSocket class can be used to create a server socket.
This object is used to establish communication with the clients.
Important methods
Method Description
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need
to pass the IP address or hostname of the Server and a port number. Here, we are using
"localhost" because our server is running on same system.
1. Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives
and prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
download this example
To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.
After running the client application, a message will be displayed on the server console.
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}