I'm trying to uso MulticastSocket between two process.
Server send packet and client need to read it. The server code is:
MulticastSocket multicastSocket = new MulticastSocket();
multicastSocket.setTimeToLive((Integer) config.getValue("MULTICAST_TTL"));
multicastSocket.setLoopbackMode(false);
multicastSocket.setReuseAddress(true);
String msg = "KA";
InetAddress multicastGroup = "225.3.0.1";
int port = 4000;
DatagramPacket pkt = new DatagramPacket(msg.getBytes(), msg.getBytes().length, multicastGroup, port);
while(true) {
try{
multicastSocket.send(pkt);
System.out.println("SPEDITO PACCHETTO: "+pkt.getSocketAddress());
}catch ( IOException e){
System.out.println("Errore di comunicazione con la rete multicast. "+e.getMessage());
}
}
The client code is:
this.multicastSocket = new MulticastSocket(4000);
InetAddress multicastGroup = InetAddress.getByName("225.3.0.1");
this.multicastSocket.joinGroup(multicastGroup);
DatagramPacket pkt = new DatagramPacket(new byte[512], 512);
while(true){
System.out.println("GOING TO READ");
multicastSocket.receive(pkt);
System.out.println("READ");
byte[] b = pkt.getData();
String msg = new String(b, 0, pkt.getLength());
}
The problem is that server send packet (send(pkt) returns), instead client not receive packate (receive(pkt) not returns). Where is the problem?
p.s.: Server and client are on same computer, and MULTICAST_TTL is 1.
Related
my programm is establishing a connection via multicastsocket between server and client. I want to send some informations to the client and then receive an answer from the client and print it out.
This works, but it always printing out the String infromation. Like it is still saved in the DatagramPacket and fill the String received with data from String information. So when i run the programm its always printing out "Server: received Message: Welcome to the Event Server"
System.out.println("Server is running...");
InetAddress infoChannel = InetAddress.getByName("225.5.6.6");
MulticastSocket info_socket = new MulticastSocket(3456);
info_socket.joinGroup(infoChannel);
String information = "Welcome to the Event Server ";
byte [] buffer = information.getBytes();
DatagramPacket info_packet = new DatagramPacket(buffer, buffer.length, infoChannel, 3456);
info_socket.send(info_packet);
System.out.println("Message send");
while(true) {
info_packet.setData(new byte[256]);
info_socket.receive(info_packet);
String received = new String(info_packet.getData(), info_packet.getOffset(), info_packet.getLength());
info_packet.setLength(info_packet.getLength());
System.out.println("Server: received Message: " + received);
}
CLient :
System.out.println("Client is waiting for Connection to Server...");
InetAddress infoChannel = InetAddress.getByName("225.5.6.6");
MulticastSocket info = new MulticastSocket(3456);
info.joinGroup(infoChannel);
byte[] buffer = new byte[350];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
info.receive(packet);
String recString = new String(buffer);
String[] lines = recString.split("#");
Arrays.stream(lines).forEach(System.out::println);
System.out.println("Enter message to send: ");
String answer = readIn.nextLine();
packet = new DatagramPacket(answer.getBytes(), answer.length(), infoChannel, 3456);
info.send(packet);
System.out.println("client: Inormation sended to Server");
info.close();
Thanks in advance!
i tried to somehow clear the buffer and then store the received message in the String received
I am trying to create a a client and server chat program using UDP. I have followed a tutorial making a similar program using TCP and tried to then translate my knowledge over to make one in similar fashion using UDP.
I have completed a client and server side with both showing no errors and will run, but once running neither will message the other or receive messages... can someone help me see what i'm doing wrong?
Server side for sending messages:
try{
//creates the packet to be sent
byte[] buf = new byte[256];
String msgout = serverText.getText().trim();
buf = msgout.getBytes();
//uses the socet.receive method to get the packet to retrieve information to send
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ss.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
//uses packet information to create and send packet
DatagramPacket packetSend = new DatagramPacket(buf, buf.length, address, port);
ss.send(packetSend);
//Displays the message in the chat area and clears the text area
serverArea.setText(serverArea.getText().trim()+"\n Server: "+msgout);
serverText.setText("");
}catch (Exception e){
}
and then the main for setting the socket and receiving/printing:
String msgin = "";
try{
ss = new DatagramSocket(1420); // Sets socket at 1420
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ss.receive(packet); //Receives the packet from the socket
//Converts the byte array into a string
String clientMsg = new String(packet.getData(), 0, packet.getLength());
while(!msgin.equals("exit")){
//Displays the message
msgin = clientMsg;
serverArea.setText(serverArea.getText().trim()+"\n Client: "+msgin); //displays client message
}
}catch(Exception e){
}
Here is the client side code, ill combine its send and receive areas into one block:
try{
//Creates the message out using the known socket that the Server creates and the known local address
String msgout = clientText.getText().trim();
sendBuf = msgout.getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket sp = new DatagramPacket(sendBuf, sendBuf.length, address, 1420);
s.send(sp);
//Displays the text and clears the text field
clientchat.setText(clientchat.getText().trim()+"\n Server: "+msgout);
clientText.setText("");
}catch (Exception e){
}
String msgin = "";
try{
//Creates a socket
DatagramSocket s = new DatagramSocket();
//Receives the message from the server
byte[] buf = new byte[256];
DatagramPacket rp = new DatagramPacket(buf, buf.length);
s.receive(rp);
//Converts byte array to message
String clientMsg = new String(rp.getData(), 0, rp.getLength());
while(!msgin.equals("exit")){
//Displays the message
msgin = clientMsg;
clientchat.setText(clientchat.getText().trim()+"\n Server: "+msgin); //displays client message
}
}catch (Exception e){
}
Any help and tips will be greatly appreciated!
If nothing is happening, and you are unable to send/receive messages, it is likely that there are exceptions that are being generated.
However, since you have a try-catch block that catches all exceptions, and then simply does nothing, you will have no idea what exceptions are thrown, if any are thrown at all.
Rather than simply ignoring exceptions, you should at least be printing their cause.
In your catch statements, add the following and you will be able to more easily debug.
e.printStackTrace();
I try to read the UDP Stream from X-Plane 12 in Java.
This is what I try:
public class EchoClient {
#Test
public void echo() throws IOException {
DatagramSocket socket;
InetAddress address;
byte[] buf;
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
String msg = "TEST";
buf = msg.getBytes();
DatagramPacket packet
= new DatagramPacket(buf, buf.length, address, 49000);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
System.out.println("hi there");
while(true) {
socket.receive(packet); // it "stops" here... without an error
String received = new String(
packet.getData(), 0, packet.getLength());
System.out.println(received);
}
}}
X-Plane is running and the UDP option is activated - but my program does print nothing on the console.. and it is runnig forever (while true)
Receive is blocked and waiting to a receive a packet. The packet you sent earlier is dropped on the floor because no one is listening.
I am triying to comunicate 2 machines through datagram sockets but I guess I am missing something...
Machine A is runs an Android App (client)
Machine B is a server writen in Python
I can send a message from A to B without any problem, but A never gets the answer from B, the code is the following:
Client (Java) :
InetAddress serverAddr = InetAddress.getByName("10.0.0.10");
DatagramSocket socket = new DatagramSocket();
byte[] bufSent = "register".getBytes();
DatagramPacket dpSent = new DatagramPacket(bufSent,bufSent.length, serverAddr, 8088);
socket.send(dpSent);
byte[] bufRecv = new byte[1024];
DatagramPacket dpReceive = new DatagramPacket(bufRecv, bufRecv.length);
socket.receive(dpReceive);
String serverMessage = new String(dpReceive.getData(), 0, dpReceive.getLength());
Log.v(LOGTAG, "Received " + serverMessage);
Server (Python):
import socket
UDP_IP_DEST = "10.0.0.11"
UDP_IP = "10.0.0.10"
UDP_PORT = 8088
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
if data:
print "received message:", data
sock.sendto("I got the message", (UDP_IP_DEST, UDP_PORT))
Does anyone see where is the mistake? The point is that I have tried to send the answer to another machine instead of the mobile and it works fine.
Thanks a lot.
I had a similar problem with receiving, here's some code we use in our app for Datagrams modified with your values, you can see we do a few things differently in the socket set up. mSocket is just a private DatagramSocket member variable. Give it a try. I think you might need to bind, and possible set the reuse address flag.
try
{
mSocket = new DatagramSocket(null);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(false);
mSocket.bind(new InetSocketAddress(8088));
//Set a 1.5 second timeout for the coming receive calls
mSocket.setSoTimeout(1500);
String data = "myData";
DatagramPacket udpPacket = new DatagramPacket(data.getBytes(), data.length(), InetAddress.getByName("10.0.0.10"), 8088);
mSocket.send(udpPacket);
byte[] buf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(buf, buf.length);
mSocket.receive(recvPacket);
String response = new String(recvPacket.getData());
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I'm implementing the example where a server listens for any active clients in the network.
I'm using Datagram sockets for the server to do the multicast and clients to respon to the server.
public void run() {
try {
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
DatagramSocket dSock = new DatagramSocket(4445);
dSock.receive(packet);
int byteCount = packet.getLength();
ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(byteStream));
}
}
and on the client's side:
public void run() {
{
ObjectOutputStream os = null;
try {
InetAddress address = InetAddress.getByName("Server's IP");//Note!
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(15000);
os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
os.flush();
os.flush();
byte[] sendBuf = byteStream.toByteArray();
DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, address, 4445);
int byteCount = packet.getLength();
}
}
}
In the above Eg, the Client has to know the server's IP apriori(hardcode). How can I modify the code on the server's side so that the server sends it's IP to the client and client responds to it?
I was able to do this using sockets but is it possible using datagram sockets?
Thanks!
You could use DatgramPacket.getAddress() and reply to the sender
Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
Try getting hostAddress using InetAddress.getHostAddress, read the IP part and pass it to a variable.
InetAddress address = InetAddress.getByName("[variable]");
or
InetAddress address = InetAddress.getByAddress("[variable]");
I hope any of these would lead to a better way.