Java Tutorial
import java.net.*; class DatagramTest { public static int serverPort = 887; public static int clientPort = 888; public static DatagramSocket ds; public static byte buffer[] = new byte[1024]; public static void serverMethod() throws Exception { int seek = 0; while(true) { int ch = System.in.read(); if (ch == -1) { System.out.println("Server exists!"); return; } else if (ch == '\n') { ds.send(new DatagramPacket(buffer, seek, InetAddress.getLocalHost(), clientPort)); seek = 0; break; } else { buffer[seek++] = (byte) ch; } } } public static void clientMethod() throws Exception { while(true) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); ds.receive(dp); System.out.println(new String(dp.getData(), 0, dp.getLength())); } } public static void main(String args[]) throws Exception { if(args[0].equals( "server")) { ds = new DatagramSocket(serverPort); serverMethod(); } else { ds = new DatagramSocket(clientPort); clientMethod(); } } }Output:
//Client step1: $ java DatagramTest client step4: hello world!
//Server step2: $ java DatagramTest server //once pressed enter key, data will be sent to client step3: hello world!
$ java DatagramTest Exception in thread "main" java.net.BindException: Permission denied (Bind failed) at java.net.PlainDatagramSocketImpl.bind0(Native Method) at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:93) at java.net.DatagramSocket.bind(DatagramSocket.java:392) at java.net.DatagramSocket.(DatagramSocket.java:242) at java.net.DatagramSocket. (DatagramSocket.java:299) at java.net.DatagramSocket. (DatagramSocket.java:271) at DatagramTest.main(DatagramTest.java:43)
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page