09 April 2016

StringUDPClient StringUDPServer

package network.sample;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class StringUDPClient {
 public static void main(String args[]) {
  try {
   DatagramSocket clientSocket = new DatagramSocket();

   // Send to Server
   String str = "Abc";
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   DataOutputStream dos = new DataOutputStream(outputStream);
   dos.writeUTF(str);

   InetAddress address = InetAddress.getByName("localhost");
   int port = 9876;

   DatagramPacket toServer = new DatagramPacket(outputStream.toByteArray(), outputStream.toByteArray().length,
     address, port);
   clientSocket.send(toServer);

   // Read from Server
   byte[] inFromServer = new byte[1024];
   DatagramPacket fromServer = new DatagramPacket(inFromServer, inFromServer.length);
   clientSocket.receive(fromServer);

   ByteArrayInputStream inputStream = new ByteArrayInputStream(fromServer.getData());
   DataInputStream dis = new DataInputStream(inputStream);
   
   String data = dis.readUTF();

   System.out.println(data);

   clientSocket.close();

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

package network.sample;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class StringUDPServer {
 public static void main(String[] args) {
  try {
   DatagramSocket serverSocket = new DatagramSocket(9876);
   System.out.println("Server Ready");

   byte[] inFromClient = new byte[1024];
   int length = inFromClient.length;

   // Receive from Client
   DatagramPacket fromClient = new DatagramPacket(inFromClient, 0, length);
   serverSocket.receive(fromClient);

   ByteArrayInputStream inputStream = new ByteArrayInputStream(fromClient.getData());
   DataInputStream dis = new DataInputStream(inputStream);

   String dataReceived = dis.readUTF();
   
   System.out.println("Nhan " + dataReceived);
   dataReceived = "Xin chao " + dataReceived;

   // Send to Client
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   DataOutputStream dos = new DataOutputStream(outputStream);

   dos.writeUTF(dataReceived);
   InetAddress address = fromClient.getAddress();
   int port = fromClient.getPort();
   DatagramPacket toClient = new DatagramPacket(outputStream.toByteArray(), outputStream.toByteArray().length,
     address, port);

   serverSocket.send(toClient);
   serverSocket.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang