Use DatagramSocket to send out and receive DatagramPacket : DatagramSocket « Network Protocol « Java






Use DatagramSocket to send out and receive DatagramPacket

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ChatClient {

  public static void main(String[] args) throws Exception {
    DatagramSocket s = new DatagramSocket();
    byte[] buf = new byte[1000];
    DatagramPacket dp = new DatagramPacket(buf, buf.length);

    InetAddress hostAddress = InetAddress.getByName("localhost");
    while (true) {
      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      String outMessage = stdin.readLine();

      if (outMessage.equals("bye"))
        break;
      String outString = "Client say: " + outMessage;
      buf = outString.getBytes();

      DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999);
      s.send(out);

      s.receive(dp);
      String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "
          + new String(dp.getData(), 0, dp.getLength());
      System.out.println(rcvd);
    }
  }
}



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ChatServer {
  public static void main(String[] args) throws Exception {
    int PORT = 4000;
    byte[] buf = new byte[1000];
    DatagramPacket dgp = new DatagramPacket(buf, buf.length);
    DatagramSocket sk;

    sk = new DatagramSocket(PORT);
    System.out.println("Server started");
    while (true) {
      sk.receive(dgp);
      String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
          + dgp.getAddress() + ", port: " + dgp.getPort();
      System.out.println(rcvd);
      
      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      String outMessage = stdin.readLine();
      buf = ("Server say: " + outMessage).getBytes();
      DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort());
      sk.send(out);
    }
  }
}

   
  








Related examples in the same category

1.DatagramSocket sends out DatagramPacket
2.DatagramSocket receives DatagramPacket
3.Datagram Sender
4.Sending a Datagram
5.Receiving a Datagram
6.Joining a Multicast Group
7.Receiving from a Multicast Group
8.Sending to a Multicast Group
9.Receive DatagramPacket
10.Send a Datagram
11.User Datagram Protocol Programming
12.Read and write with DatagramPacket
13.Send back the response in a DatagramPacket