Advertisement
godens

Server

Mar 8th, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.DatagramPacket;
  3. import java.net.DatagramSocket;
  4. import java.net.InetAddress;
  5. import java.net.SocketException;
  6. import java.nio.channels.DatagramChannel;
  7.  
  8. public class Server3 extends Thread{
  9.    
  10.     byte[] sendData = new byte[50];
  11.     boolean isRunning;
  12.     InetAddress ipAddr;
  13.     int portNb;
  14.     DatagramSocket sendSock;
  15.    
  16.     public Server3(InetAddress ipAddr, int portNb) throws SocketException {
  17.         super();
  18.         this.ipAddr = ipAddr;
  19.         this.portNb = portNb;
  20.         sendSock = new DatagramSocket();
  21.         DatagramChannel channel = null;
  22.         try {
  23.             channel = DatagramChannel.open();
  24.         } catch (IOException e) {
  25.             e.printStackTrace();
  26.         }
  27.         sendSock = channel.socket();
  28.         sendSock.setReuseAddress(true);
  29.     }
  30.  
  31.     @Override
  32.     public void run() {
  33.        
  34.         while(isRunning){
  35.            
  36.             sendData = "server msg here".getBytes();
  37.            
  38.             DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddr, portNb);
  39.             try {
  40.  
  41.                 sendSock.send(sendPacket);
  42.                 Thread.sleep(1000);
  43.                 System.out.println("sent msg");
  44.                
  45.             } catch (IOException e) {
  46.                 e.printStackTrace();
  47.             } catch (InterruptedException e) {
  48.                 e.printStackTrace();
  49.             }
  50.            
  51.         }
  52.     }
  53.    
  54.     public void startSending(){
  55.         isRunning=true;
  56.         start();
  57.     }
  58.    
  59.     public void stopReceiving(){
  60.         isRunning=false;
  61.     }
  62.    
  63.     public static void main(String[] args) throws IOException {
  64.         Server3 s = new  Server3(InetAddress.getByName("10.0.2.2"),57111);
  65.         s.startSending();
  66.        
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement