0% found this document useful (0 votes)
26 views

Sender Receiver

This document contains code for a datagramSender class and a datagramReceiver class that communicate via UDP. The datagramSender takes a host, port, and message as arguments, creates a DatagramSocket, and sends the message bytes as a DatagramPacket to the given host and port. The datagramReceiver listens on a given port for a DatagramPacket, receives the message bytes, and prints the message string.

Uploaded by

ladyj4483
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Sender Receiver

This document contains code for a datagramSender class and a datagramReceiver class that communicate via UDP. The datagramSender takes a host, port, and message as arguments, creates a DatagramSocket, and sends the message bytes as a DatagramPacket to the given host and port. The datagramReceiver listens on a given port for a DatagramPacket, receives the message bytes, and prints the message string.

Uploaded by

ladyj4483
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.net.*; import java.io.

*; public class datagramSender { public static void main(String[] args) { try{ InetAddress receiverHost = InetAddress.getByName(args[0]); int receiverPort = Integer.parseInt(args[1]); String message = args[2]; DatagramSocket mySocket = new DatagramSocket(); byte[] buffer = message.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, receiverHost, receiverPort); mySocket.send(packet); mySocket.close(); } catch(Exception e){} } } import java.net.*; import java.io.*; public class datagramReceiver { public static void main(String[] args) { try{ int MAX_LEN = 16; int localPortNumber = Integer.parseInt(args[0]); DatagramSocket mySocket = new DatagramSocket(localPortNumber); byte[] buffer = new byte[MAX_LEN]; DatagramPacket packet = new DatagramPacket(buffer, MAX_LEN); mySocket.receive(packet); // receiver is blocked here until it gets the message String message = new String(buffer); System.out.println(message); mySocket.close(); } catch(Exception e){e.printStackTrace();} } }

You might also like