1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| package xyz.onns.chat;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException;
public class MySender implements Runnable { DatagramSocket socket = null; BufferedReader reader = null; private String toIP; private int fromPort; private int toPort;
public MySender(String toIP, int fromPort, int toPort) { this.toIP = toIP; this.fromPort = fromPort; this.toPort = toPort; try { socket = new DatagramSocket(fromPort); reader = new BufferedReader(new InputStreamReader(System.in)); } catch (SocketException e) { e.printStackTrace(); } }
@Override public void run() { while (true) { try { String data = reader.readLine(); byte[] buffer = data.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(toIP, toPort)); socket.send(packet); if (data.trim().equals("bye")) { break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
|