官术网_书友最值得收藏!

Socket programming for UDP

Java supports both TCP and UDP through the Socket and DatagramSocket classes from the java.net package. Other components of this package foster communication between processes over the network using an IP address. A new socket object can be instantiated through the socket name or InetAddress and the port on which the process is running on the host.

As seen earlier, TCP is considered consistent in terms of receiving data in packets the same order as they are sent and with guaranteed delivery. If the next packet is not received in a defined period of time, then the receiver requests it again. The receiver keeps waiting until the packet is received and doesn't move further. In the UDP protocol, it's the other way round: it doesn't guarantee delivery of packets and doesn't even care about the order in which packets are received. UDP is used only when the entire information can be bundled into a single packet and there is no dependency on the other packet. Therefore, the usage of UDP is quite limited, whereas TCP is widely used in IP applications. UDP sockets are used where limited bandwidth is available, and the overhead associated with resending packets is not acceptable.

To connect using a UDP socket on a specific port, use the following code:

DatagramSocket udpSock = new DatagramSocket(3000);

If you don't care about the port number, then the default constructor can also be used for instantiation. In that case, an unused port will be used. We can find which port is used by referring to the following code:

int portNo = udpSock.getLocalPort();

A datagram is a self-contained, independent message whose time of arrival, confirmation of arrival over the network, and content cannot be guaranteed.

DatagramPacket objects are used to send data over DatagramSocket. Every DatagramPacket object consists of a data buffer, a remote host to whom the data needs to be sent, and a port number on which the remote agent would be listened. Here's sample code for doing this:

byte[] dataBuff = {'a', 'k', ' ', 'v', 'w', 'x', 'p', 'e'};
InetAddress inetAddr = InetAddress.getByName("www.google.com");
DatagramPacket dgPkt = new DatagramPacket(dataBuff, dataBuff.length, inetAddr, 5100);
udpSock.send(dgPkt);

By invoking the receive() method on DatagramSocket, a remote process can receive data. DatagramSocket received by the remote process has the host address, port number, and the buffered data.

As a good programming practice, one should do proper exception handling while establishing a connection and sending/receiving data (for example, IOException could be thrown while you perform read and write operations to streams).

The following example is a program of the UDP server that accepts the request from the client, receives the data from the client as a datagram, and responds with the server response:

//UDP Server

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class SimpleUDPServer {
public static void main(String args[]) {
DatagramSocket dgSocket = null;
if (args.length <= 0) {
System.out.println("Please pass the port number for UDPServer");
// exit the program if no port number passed
System.exit(1);
}
try {
int socketNumber = Integer.valueOf(args[0]).intValue();
dgSocket = new DatagramSocket(socketNumber);
byte[] byteBuffer = new byte[1000];
while (true) {
DatagramPacket dgRequest = new DatagramPacket(
byteBuffer, byteBuffer.length);
dgSocket.receive(dgRequest);
DatagramPacket dgresponse = new DatagramPacket(
dgRequest.getData(), dgRequest.getLength(),
dgRequest.getAddress(), dgRequest.getPort());
dgSocket.send(dgresponse);
}
} catch (SocketException e) {
System.out.println("Socket Exception : " + e.getMessage());
} catch (IOException e) {
System.out.println("IO Exception : " + e.getMessage());
} finally {
if (dgSocket != null)
dgSocket.close();
}
}
}

The following client program is used to create a datagram, send it to the preceding server program (in the server), and receive the response:

//UDP Client

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class SimpleUDPClient {
public static void main(String args[]){
// pass the message, server host and port number as arguments
DatagramSocket dgSocket = null;
if (args.length < 3) {
System.out.println(
" Pass the arguments for SimpleUDPClient in the order :
test message,
Server Host name and Port number respectively");
System.exit(1);
}
try {
dgSocket = new DatagramSocket();
byte [] bytes = args[0].getBytes();
InetAddress serverHost = InetAddress.getByName(args[1]);
int serverPortNumber = Integer.valueOf(args[2]).intValue();
DatagramPacket dgRequest =
new DatagramPacket(bytes, args[0].length(), serverHost,
serverPortNumber);
dgSocket.send(dgRequest);
byte[] byteBuffer = new byte[1000];
DatagramPacket dgResponse = new DatagramPacket
(byteBuffer, byteBuffer.length);
dgSocket.receive(dgResponse);
System.out.println("Datagram Response: " +
new String(dgResponse.getData()));
}
catch (SocketException e) {
System.out.println("Socket Exception: " + e.getMessage());
}
catch (IOException e) {
System.out.println("IO Exception : " + e.getMessage());
}
finally {
if (dgSocket != null)
dgSocket.close();
}
}
}

 

主站蜘蛛池模板: 抚远县| 四平市| 垫江县| 宾川县| 五大连池市| 苏州市| 石屏县| 玉田县| 衡山县| 平罗县| 廊坊市| 吉林市| 苍山县| 双牌县| 韩城市| 阿图什市| 锦州市| 突泉县| 东阳市| 新密市| 莱西市| 全椒县| 宁阳县| 周宁县| 永嘉县| 彩票| 安陆市| 夏邑县| 永吉县| 呈贡县| 荣昌县| 抚远县| 南涧| 甘洛县| 武强县| 佛山市| 乌拉特后旗| 广宗县| 桂阳县| 乐东| 元阳县|