|
| 1 | +package main.java.emoji_manager.msg; |
| 2 | + |
| 3 | +import java.net.DatagramPacket; |
| 4 | +import java.net.DatagramSocket; |
| 5 | +import java.net.InetAddress; |
| 6 | +import java.nio.charset.StandardCharsets; |
| 7 | + |
| 8 | +public class Sender { |
| 9 | + /* local ip */ |
| 10 | + public static String localIP = "127.0.0.1"; |
| 11 | + /* wrong message */ |
| 12 | + public static String err_msg = ""; |
| 13 | + /* default send port */ |
| 14 | + public static int SendPort = 5555; |
| 15 | + /* default chat port */ |
| 16 | + public static int chatPort = 6666; |
| 17 | + |
| 18 | + public Sender() { |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * @param msgType message Type |
| 23 | + * @return send success or not |
| 24 | + */ |
| 25 | + public static boolean sendUDPMsg(int msgType, String uname, String friendIP, int friendPort, String message) { |
| 26 | + try { |
| 27 | + /* From Common line get to send context, convert to string by UTF-8 */ |
| 28 | + byte[] msg = (msgType + "*" + uname + "*" + message).getBytes(StandardCharsets.UTF_8); |
| 29 | + /* get the host internet Address */ |
| 30 | + InetAddress address = InetAddress.getByName(friendIP); |
| 31 | + |
| 32 | + /* Initializes a datagram packet (packet) with data and address*/ |
| 33 | + DatagramPacket packet = new DatagramPacket(msg, msg.length, address, |
| 34 | + friendPort); |
| 35 | + |
| 36 | + /* Create a default socket and send packets through this socket */ |
| 37 | + DatagramSocket dSocket = new DatagramSocket(); |
| 38 | + dSocket.send(packet); |
| 39 | + |
| 40 | + /* Close the socket after sending */ |
| 41 | + dSocket.close(); |
| 42 | + } catch (Exception e) { |
| 43 | + e.printStackTrace(); |
| 44 | + err_msg = "System error!"; |
| 45 | + return false; |
| 46 | + } |
| 47 | + return true; |
| 48 | + } |
| 49 | +} |
0 commit comments