DataGram(UDP)
Socket Programming In Java
What socket is? Socket is an interface in network to communicate
between device in internet protocol, the communication are data and
information interchange. So what socket programming is?, socket
programming is creation application using socket API(Application
Programming Interface) for interchange data. Socket application
can be divided in two category based on how data sent. Data can be
sent use Datagram Socket( Using UDP) or Stream Socket (using TCP).
There are different treatment between UDP and TCP, even both are the
same function for data interchange.
UDP Datagram Sockects in Java
in UDP connection process first for sending data, data package can be
sent without need to connect first between server and client,
client can can straight send data to the server. When you create
server class make sure that the port is not in conflict, such as for
http, database or something else. In this I use port 3000
import
java.net.DatagramPacket;
import
java.net.DatagramSocket;
import
java.net.InetAddress;
class
UDPServer{
public
static
void
main(String args[]) throws
Exception{
// determine socket and the port
DatagramSocket
serverSocket = new
DatagramSocket(3000);
//
variable put data for sending and receive
byte[]
receiveData = new
byte[1024];
byte[]
sendData = new
byte[1024];
while(true){
//
for reading data packet that has been sent by client
DatagramPacket
receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String
sentence = new
String( receivePacket.getData());
System.out.println("data
received from client: " +
sentence);
//
this how to send datapacket
to client
//
i just send back data client has been sent
InetAddress ip
= receivePacket.getAddress();
int
port = receivePacket.getPort();
sendData =
sentence.getBytes();
DatagramPacket
sendPacket = new
DatagramPacket(sendData,
sendData.length,
ip, port);
serverSocket.send(sendPacket);
}
}
}
Now let’s create client for sending data Data, the idea is user can type any sentences in console after he or she finish typed sentences and press enter the data will send,
import
java.io.BufferedReader;
import
java.io.InputStreamReader;
import
java.net.DatagramPacket;
import
java.net.DatagramSocket;
import
java.net.InetAddress;
public
class
UDPClientSecond {
public
static
void
main(String args[]) throws
Exception{
// for retrieve sentences that that
// has user has typed in console
BufferedReader userInput = new
BufferedReader(new
InputStreamReader(System.in));
// Create socket for sending data
DatagramSocket clientSocket = new
DatagramSocket();
InetAddress ip = InetAddress.getByName("localhost");
// determine variable for put
// send data and receive data
byte[]
sendData = new
byte[1024];
byte[]
receiveData = new
byte[1024];
// convert sentences to byte for
sending
// to server
String sentence = userInput.readLine();
sendData = sentence.getBytes();
// create data packet and send
using socket
DatagramPacket sendPacket = new
DatagramPacket(sendData,
sendData.length,
ip, 3000);
clientSocket.send(sendPacket);
// retrieve data send from server
DatagramPacket receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String sentencesServer = new
String(receivePacket.getData());
System.out.println("sentences
from server :"
+ sentencesServer);
clientSocket.close();
}
}
for running both class, because I used eclipse for making both class, you just do right click in each classes and select run as → java application, perhaps we might give a little concern how to interchange console, the are icon for interchange console and show option which console you want to see.
![shabbynote console interchange shabbynote console interchange](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY9Q_AdV2GDKdqqMOZ0RqCXlXTQoAYAj6aNSdC7nY8GIF22RcdIKP3S4BQvoEIJDyfutWLiocPTSmMkkIlRTkpYuNNHzDKNVyj1jhna9T7rMD5gk9eRPAkwzGErXcqjsxn0g1tJe2RiLo/s640/console_interchange.JPG) |
Console Interchange |
I run both class
first I run server first the second I run the client. Here the screen shot :
![shabbynote client input shabbynote client input](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_ZxLYHMHrv5SCDoNVgm7agAlrZp1ilWMx_RViLoOEe-5wah8FEzqb8xHPIC6-BDC5Whcz9IwXHj4V1AspaZrBLtMBRqDuiDRlSZahUn7tl8pCftQfks3XS4_uRq49rdOymSYPhnc_6Sw/s640/console_client.JPG) |
client input text |
after I click enter
![shabbynote after enter shabbynote after enter](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOBmS-438R48MDJ2U0pJa-GIgyor0OwLES-98ADxmoIqAxNEC5tno-gKCAcJK-_w2UIetoi1jRQJCDhYj63oqh-X9G2lR7mswrkKhPMMTZOdF_ZpHErTJhbCCkLloAYBaTnd-kLfunDQY/s640/after-enter.JPG) |
after enter |
the console of server
![shabbynote server response shabbynote server response](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2uvkIxkO_fp5Q4xCygSeQyBoDNkolS5uLsLsU4WI4iDvE47sjXVcdkLdACB49nRfKgstri6JMjYc6KxaZ2dGzp64woQd6XuzZvoKP-EXYUZErrvaHaVpvNnSTR2bNagU0lP2rDMzvQbk/s640/server-console.JPG) |
server response |
the weakness of using UDP once you send message multiple sometime the sequence message that you have been send be unordered, you can try with with code above but you send mutiple message the data be mess up. This the screen shoot result my trial :
![shabby note multiple mesage shabby note](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOZ8kgDx1ULXo3xGZJRjTl8wpaSR68GUbLEvKxkdHNJRkHXm4eIiXYKi2ZoADSjiLgtH0DBjgRpdLm-Qokw-kkwPm77GHxEo4AXgf4Q2YRIzTzP2bWnfxKmd6JxdCkohOb0-zAnNQYAQE/s640/multiple_message.JPG) |
for multiple messages |