Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package UDP_Cau3;
- import UDP_MulThread_guess.UDP_thread_client;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- import java.util.Scanner;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author koman
- */
- public class client {
- public static void sendPacket(int number , DatagramSocket ds) throws UnknownHostException, IOException
- {
- String tmp = String.valueOf(number);
- byte m[] = tmp.getBytes();
- InetAddress addr = InetAddress.getByName("localhost");
- DatagramPacket dp = new DatagramPacket(m,m.length,addr,1338);
- ds.send(dp);
- }
- public static String receivePacket_str(DatagramSocket ds) throws IOException
- {
- byte m[] = new byte[256];
- DatagramPacket dp = new DatagramPacket(m,m.length);
- ds.receive(dp);
- String mess = new String(dp.getData()).trim();
- return mess;
- }
- public static class Sender extends Thread
- {
- DatagramSocket ds;
- public Sender(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- try {
- sendPacket(1,ds);
- Scanner ip = new Scanner(System.in);
- System.out.print("Please give me my magic : ");
- while(true)
- {
- try {
- int number = ip.nextInt();
- sendPacket(number,ds);
- } catch (IOException ex) {
- Logger.getLogger(UDP_thread_client.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- } catch (IOException ex) {
- Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- public static class Receiver extends Thread
- {
- DatagramSocket ds;
- public Receiver(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- while(true)
- {
- try {
- String mess = receivePacket_str(ds);
- if ( mess.contains("winner") || mess.contains("lose") )
- {
- System.out.println(mess);
- System.exit(0);
- }
- else System.out.println(mess);
- } catch (IOException ex) {
- Logger.getLogger(UDP_thread_client.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- }
- public static void main(String[] args) throws SocketException
- {
- DatagramSocket ds = new DatagramSocket();
- Sender send = new Sender(ds);
- send.start();
- Receiver receive = new Receiver(ds);
- receive.start();
- }
- }
Add Comment
Please, Sign In to add comment