- //UDPCLIENT
- import java.io.*;
- import java.net.*;
- public class client
- {
- public static void main(String args[])
- {
- try
- {
- DatagramSocket socket=new DatagramSocket();
- byte [] buff=new byte[1024];
- InetAddress address=InetAddress.getByName("localhost");
- System.out.println("Trying...to connect to the server.");
- while(true)
- {
- System.out.println("Enter data");
- BufferedReader buff_data=new BufferedReader(new InputStreamReader(System.in));
- String user_data=buff_data.readLine();
- buff=user_data.getBytes();
- DatagramPacket packet=new DatagramPacket(buff,buff.length,address,4455);
- socket.send(packet);
- }
- }
- catch(UnknownHostException unknown_host)
- {
- System.out.println("Unknown host..");
- unknown_host.printStackTrace();
- }
- catch(SocketException socket_error)
- {
- System.out.println("Some socket error has occured.");
- socket_error.printStackTrace();
- }
- catch(IOException input_error)
- {
- System.out.println("Some input error has occured.");
- input_error.printStackTrace();
- }
- }
- }
- //UDPSERVER
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.io.IOException;
- import java.net.SocketException;
- public class server
- {
- public static void main(String args[])
- {
- new server().chatting();
- }
- public void chatting()
- {
- try
- {
- DatagramSocket socket=new DatagramSocket(4455);
- byte[] buff=new byte[1024];
- while(true)
- {
- DatagramPacket packet=new DatagramPacket(buff,buff.length);
- socket.receive(packet);
- String client_packet=new String(packet.getData(),0,packet.getLength());
- System.out.println("Received a packet from client "+client_packet);
- }
- }
- catch(SocketException socket_error)
- {
- System.out.println("Socket exception has occured.");
- socket_error.printStackTrace();
- }
- catch(IOException input_error)
- {
- System.out.println("Input error has occured.");
- input_error.printStackTrace();
- }
- }
- }
2023 characters | 82 lines | 1.98 KB
