Answer the question
In order to leave comments, you need to log in
How to ignore when receiving broadcast messages from itself?
The class can send broadcast udp messages. How to make it so that it does not accept messages sent by itself?
package com.company.Network;
import java.io.*;
import java.net.*;
import java.util.LinkedList;
import Old.Message.Message;
import Tubes.Tube;
/**
* @class Network
* класс-поток для работы с сетью
*/
public class Network implements Runnable {
private Tube m_in;
private Tube m_out;
private final int m_port = 1300;
private DatagramSocket m_socket;
public Network() {
}
public void setTubes(Tube in, Tube out) {
m_in = in;
m_out = out;
}
///отправить сообщение в сеть
private void sendData(byte [] data) throws Exception {
if(m_socket == null) {
return;
}
DatagramPacket dp = new DatagramPacket(data, data.length,
InetAddress.getByName("255.255.255.255"),
m_port);
m_socket.send(dp);
}
///сериализовать
public byte[] serialize (Message msg) throws Exception {
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
ObjectOutputStream oos =
new ObjectOutputStream(baos);
oos.writeObject(msg);
return baos.toByteArray();
}
///десериализовать
public Message deSerialize(byte[] serialized) throws Exception {
ByteArrayInputStream bais =
new ByteArrayInputStream(serialized);
ObjectInputStream ois =
new ObjectInputStream(bais);
return (Message)ois.readObject();
}
///принять данные из сети
private void receiveData() {
DatagramPacket dp;
byte [] data = new byte[1024];
dp = new DatagramPacket(data, data.length);
try {
m_socket.receive(dp);
m_in.enqueue(deSerialize(data));
} catch (Exception e) {
System.out.println(e.toString());
}
}
///основнойметод потока
@Override
public void run() {
//открытие сокета
try {
m_socket = new DatagramSocket(m_port);
} catch (Exception e) {
System.out.println(e.toString());
m_socket.close();
return;
}
//чтение полученных сообщений
while (true) {
//есть что отправлять
if(!m_out.isEmpty()) {
try {
sendData(serialize(m_out.dequeue()));
} catch(Exception e) {
System.out.println(e.toString());
}
}
//получить данные
receiveData();
}
}
}
Answer the question
In order to leave comments, you need to log in
Until you receive a message, you cannot understand whether it is addressed to you or not, you can play around with the routing on the router or what is used there.
I received a message and realized that it was from me. Those. no methods?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question