Java Network Programming
Java Network Programming
2) Protocol
A protocol is a set of rules basically that is followed for communication. For
example:
TCP
FTP
Telnet
SMTP
POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with
unique MAC.
6) Socket
A socket is an endpoint between two way communication.
Visit next page for java socket programming.
Java Socket Programming
• Java Socket programming is used for communication between the applications
running on different JRE.
• Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server, server reads the message and prints it. Here, two
classes are being used: Socket and ServerSocket. The Socket class is used to
communicate client and server. Through this class, we can read and write message.
The ServerSocket class is used at server-side. The accept() method of ServerSocket
class blocks the console until the client is connected. After the successful connection
of client, it returns the instance of Socket at server-side. (See Next slide)
Socket class
•A socket is simply an endpoint for communications between the machines.
The Socket class can be used to create a socket.
Important methods
Method Description
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.
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);}
}
}
• 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.