Multicast server receive the same data it sends - java

I'm trying to allow clients that connect to my UDP server to send packets to the server, I have a server running so packets can be sent to the clients, but trying to send packets back via the client to the server seems to create some weird errors.
If I start the server, then open a client, the client will receive the first packet from the server, the client then tries to send the packet to the server, this is received by the server, but then the client throws this error
Exception in thread "main" java.lang.NumberFormatException: For input string: "testing"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Pong.PongUDPClient.main(PongUDPClient.java:71)
Line 71 will be pointed at in the code
The server console is just printing out the data it should be sending to the client,
Here is the whole code for the server
package Pong;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;
//This is the actual server
public class PongUDPServerThread extends Thread {
//speed to send data
private long dataSpeed = 10;
private int port = 4447;
private int idPlayer = 0;
private PongModel model;
private PongView view;
private PongPlayerThread players[] = new PongPlayerThread[2];
private MulticastSocket socket = null;
private InetAddress group;
private DatagramPacket packet = null;
private int ID = 1;
public PongUDPServerThread() throws IOException
{
super("PongUDPServerThread");
}
public String rtnInfo()
{
String str;
str = model.getBall().getX() + ":" +
model.getBall().getY() + ":" +
model.getBats()[0].getX() + ":" +
model.getBats()[0].getY() + ":" +
model.getBats()[1].getX() + ":" +
model.getBats()[1].getY();
return str;
}
public void setupPong() throws IOException
{
System.out.println("Pong");
model = new PongModel();
view = new PongView();
new PongController( model, view );
model.addObserver( view ); // Add observer to the model
//view.setVisible(true); // Display Screen
model.makeActiveObject(); // Start play
//start server
socket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.setReuseAddress(true);
socket.joinGroup(group);
//socket.setReuseAddress(true);
//Inform server user
System.out.println("Server is running");
}
public void run()
{
//Server loop
while(true)
{
//Receive the data
try
{
byte[] receiveBuf = new byte[256];
packet = new DatagramPacket(receiveBuf, receiveBuf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(received);
}
catch (IOException e)
{
}
try
{
byte[] buf = new byte[256];
//Gather data
buf = rtnInfo().getBytes();
//System.out.println(buf.toString());
//Send data
packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("230.0.0.1"), port);
socket.send(packet);
//Sleep the server
try
{
sleep((long)dataSpeed);
}
catch (InterruptedException e)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
//socket.close();
}
}
Here is the client code
package Pong;
import java.io.*;
import java.net.*;
import java.util.*;
public class PongUDPClient {
private static int port = 4447;
public static void main(String[] args) throws IOException
{
//Setup pong rdy
PongModel model = new PongModel();
PongView view = new PongView();
new PongController( model, view );
model.addObserver( view ); // Add observer to the model
String pos;
model.makeActiveObject(); // Start play
//model.clientModel();
MulticastSocket socket = new MulticastSocket(port);
//socket.setReuseAddress(true);
InetAddress address = InetAddress.getByName("230.0.0.1");
//Join the UDP list port
socket.setReuseAddress(true);
socket.joinGroup(address);
DatagramPacket packet;
view.setVisible(true); // Display Screen
System.out.println("Connected");
//Id is sent here.
while(true)
{
//Send data to server
try
{
byte[] receiveBuf = new byte[256];
//Gather data
receiveBuf = "testing".getBytes();
//System.out.println(buf.toString());
//Send data
packet = new DatagramPacket(receiveBuf, receiveBuf.length, InetAddress.getByName("230.0.0.1"), port);
socket.send(packet);
//Sleep the server
}
catch (IOException e)
{
e.printStackTrace();
}
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
//System.out.println("Server data: " + received);
String[] posValues = received.split(":");
model.getBall().setX(Double.parseDouble(posValues[0])); // <-- Line 71
model.getBall().setY(Double.parseDouble(posValues[1]));
model.getBats()[0].setX(Double.parseDouble(posValues[2]));
model.getBats()[0].setY(Double.parseDouble(posValues[3]));
model.getBats()[1].setX(Double.parseDouble(posValues[4]));
model.getBats()[1].setY(Double.parseDouble(posValues[5]));
//Check for keyboard input
if(PongController.moveUp == true && PongController.moveDown == false)
{
System.out.println("Up");
PongController.moveUp = false;
}
else if(PongController.moveUp == false && PongController.moveDown == true)
{
System.out.println("Down");
PongController.moveDown = false;
}
else
{
//serverOut.println("nothing");
}
}
}
}
Been stuck on this for awhile, and can't seem to find any tutorials on how to send packets from client to server using Multicast.

You are experiencing multicast loopback. Turn it off with MulticastSocket#setLoopbackMode(true), or, if that peer is just sending to the multicast group, not receiving, it doesn't need to join the group at all.

Related

Receive message from multicast socket on another host (from aws server instance)

I want to send/receive messages by the multicast socket.
This is my code
'''
public class MulticastSender {
public static final String GROUP_ADDRESS = "230.0.0.1";
public static final int PORT = 7766;
public static void main(String[] args) throws InterruptedException {
DatagramSocket socket = null;
try {
// Get the address that we are going to connect to.
InetAddress address = InetAddress.getByName(GROUP_ADDRESS);
System.out.println("GROUP_ADDRESS: " + address);
// Create a new Multicast socket
socket = new DatagramSocket();
DatagramPacket outPacket = null;
long counter = 0;
while (true) {
String msg = "Sent message No. " + counter;
counter++;
outPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, address, PORT);
socket.send(outPacket);
System.out.println("Server sent packet with msg: " + msg);
Thread.sleep(1000); // Sleep 1 second before sending the next message
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
'''
'''
public class MulticastReceiver {
public static final byte[] BUFFER = new byte[4096];
public static void main(String[] args) {
MulticastSocket socket = null;
DatagramPacket inPacket = null;
try {
// Get the address that we are going to connect to.
SocketAddress address = new InetSocketAddress(MulticastSender.GROUP_ADDRESS, MulticastSender.PORT);
// Create a new Multicast socket
socket = new MulticastSocket(address);
socket.joinGroup(address, NetworkInterface.getByName("eth0"));
while (true) {
// Receive the information and print it.
inPacket = new DatagramPacket(BUFFER, BUFFER.length);
socket.receive(inPacket);
// System.out.println(socket.getInterface());
String msg = new String(BUFFER, 0, inPacket.getLength());
System.out.println("From " + inPacket.getAddress() + " Msg : " + msg);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
'''
It is working on my local host. however, I want to send messages from my AWS server instance (with public ipv4) and receive them in the local client. How to do it?
if yes, please give me an example!
Tks all

How to run 2 main methods in parallel threads?

I have two following classes (including only main methods for simplicity)
public class UDPServer {
public static void main(String[] args) throws IOException {
int serverPort = 9876;
DatagramSocket socket = new DatagramSocket(serverPort);
byte[] buffer = new byte[1024];
boolean isConnected = true;
while (isConnected) {
try {
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
socket.receive(request);
DatagramPacket reply = new DatagramPacket(
request.getData(),
request.getLength(),
request.getAddress(),
request.getPort()
);
socket.send(reply);
} catch (IOException ex) {
isConnected = false;
Logger.getLogger(UDPServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class UDPClient {
public static void main(String[] args) {
String pathToQuery = getUserInput();
List<Packet> queried = UDPServer.getQueriedServerDataTypes(pathToQuery);
try {
if (args.length < 1) {
System.out.println("Usage: UDPCLient <msg> <server host name>");
System.exit(-1);
}
// Create a new datagram socket
DatagramSocket socket = new DatagramSocket();
// Preferred IPv4 address (cmd: ipconfig/all)
InetAddress host = InetAddress.getByName(args[0]);
int serverPort = 9876;
for (int i = 0; i < queried.size(); i++) {
Packet dataType = queried.get(i);
String requestFile = "data_type_request_v" + (i + 1) + ".txt";
UDPServer.saveToFile(
dataType,
"Server request.",
requestFile
);
// Serialize Packet object to an array of bytes
byte[] data = Tools.serialize(dataType);
System.out.println("Sent: " + Arrays.toString(data));
// Request datagram packet will store data query for the server
DatagramPacket request = new DatagramPacket(
Objects.requireNonNull(data),
data.length,
host,
serverPort
);
// Send serialized datagram packet to the server
socket.send(request);
// The reply datagram packet will store data returned by the server
DatagramPacket reply = new DatagramPacket(data, data.length);
System.out.println("Reply: " + Arrays.toString(reply.getData()));
// Acquire data returned by the server
socket.receive(reply);
// Store deserialized data in null Packet object.
Packet read = (Packet) Tools.deserialize(data);
System.out.println("Reading deserialized data...\n" + read.toString());
String responseFile = "data_type_response_v" + (i + 1) + ".txt";
UDPServer.saveToFile(
read,
"Server response.",
responseFile
);
boolean isResponseEqualRequest = UDPServer.isResponseEqualRequest(
requestFile,
responseFile
);
if (isResponseEqualRequest) {
System.out.println("Communication successful. Server response corresponds to the request.");
} else {
System.out.println("Communication unsuccessful. Server response does not correspond to the request.");
}
}
// Close the datagram socket
socket.close();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
In order for the UDPClient to work properly, UDPServer has to be running in the background. I want to run the UDPServer.main() in parallel thread and as soon as UDPClient.main() finishes, the thread should terminate as well.
How do I do that?

coding UDP communication in JavaFx

I have trouble coding UDP communication in JavaFx.
The code is capable of sending message but is not capable of receiving message.
What I should revise in the source code to receive the message?
Here is the source code:
public class JavaFXApplication10 extends Application {
public DatagramSocket receivesocket;
public DatagramPacket receivepacket;
public DatagramSocket sendsocket;
public DatagramPacket sendpacket;
public InetSocketAddress remoteAdress;
public Label label_IP;
public TextField tx_IP;
public Label label_SENDPORT;
public Label label_RECEIVEPORT;
public TextField tx_SENDPORT;
public TextField tx_RECEIVEPORT;
public Button bt_co;
public Button bt_start ;
private String message;
private XYChart.Series series;
private Timeline timer;
private static String IP = "192.168.121.23";
private static Integer SENDPORT = 12345;
private static Integer RECEIVEPORT = 12345;
public double time_counter=0.0;
private String text;
private byte[] b;
#Override
public void start(Stage stage) throws Exception{
/* text */
tx_IP = TextFieldBuilder.create().text(IP).build();
/* text */
tx_SENDPORT = TextFieldBuilder.create().text(""+SENDPORT).build();
/* text */
tx_RECEIVEPORT = TextFieldBuilder.create().text(""+RECEIVEPORT).build();
/*button */
bt_co = ButtonBuilder.create().text("Connection")
.prefWidth(200)
.alignment(Pos.CENTER)
.id("connect")
.build();
/* button_start */
bt_start = ButtonBuilder.create().text("START")
.id("start")
.build();
/* timer */
timer = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
time_counter = time_counter+1; // time
}
}));
timer.setCycleCount(Timeline.INDEFINITE);
timer.play();
/*figure*/
stage.setTitle("Line Chart Sample");
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Time [s]");
yAxis.setLabel("Force [N]");
//creating the chart
final LineChart<Number,Number> lineChart =
new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setTitle("");
//defining a series
series = new XYChart.Series();
series.setName("Force");
series.getData().add(new XYChart.Data(0.0,0.0));
lineChart.getData().add(series);
HBox root1 = HBoxBuilder.create().spacing(100).children(tx_IP ,tx_SENDPORT,tx_RECEIVEPORT).build();
HBox root2 = HBoxBuilder.create().spacing(50).children(bt_co).build();
HBox root3 = HBoxBuilder.create().spacing(25).children(bt_start).build();
VBox root4 = VBoxBuilder.create().spacing(25).children(root1,root2,root3,lineChart).build();
Scene scene = new Scene(root4);
recieve_UDP();
scene.addEventHandler(ActionEvent.ACTION,actionHandler);
stage = StageBuilder.create().width(640).height(640).scene(scene).title(" ").build();
stage.show();
}
private void recieve_UDP() throws SocketException, IOException {
ScheduledService<Boolean> ss = new ScheduledService<Boolean>()
{
#Override
protected Task<Boolean> createTask()
{
Task<Boolean> task = new Task<Boolean>()
{
#Override
protected Boolean call() throws Exception
{
receivesocket = null;
byte[] receiveBuffer = new byte[1024];
receivepacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
receivesocket = new DatagramSocket(RECEIVEPORT);
receivesocket.receive(receivepacket);
message = new String(receivepacket.getData(),0, receivepacket.getLength());
System.out.println(message);
receivesocket.close();
return true;
};
};
return task;
}
};
ss.start();
}
EventHandler<ActionEvent> actionHandler = new EventHandler<ActionEvent>(){
public void handle (ActionEvent e){
//////////////////////////////////////////////////////////////////////////////
Button src =(Button)e.getTarget();
text = src.getId();
System.out.println(text);
b = new byte[5];
if(text == "connect"){
String text_IP = tx_IP.getText();
label_IP.setText(text_IP);
IP = text_IP;
String text_SENDPORT = tx_SENDPORT.getText();
label_SENDPORT.setText(text_SENDPORT);
SENDPORT = Integer.parseInt( text_SENDPORT);
String text_RECEIVEPORT = tx_RECEIVEPORT.getText();
label_RECEIVEPORT.setText(text_RECEIVEPORT);
RECEIVEPORT = Integer.parseInt(text_RECEIVEPORT);
}
else{
remoteAdress = new InetSocketAddress(IP, SENDPORT);
sendsocket = null;
try {
sendsocket = new DatagramSocket();
} catch (SocketException ex) {
Logger.getLogger(JavaFXApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(text=="start"){
b[0] = (byte)0x02;
text ="OK";
}
else{
}
Send_UDP();
///////////////////////////////////////////////////////
}
};
public void Send_UDP(){
///////////////////////////////////////////////////////
if(text=="OK"){
sendpacket = new DatagramPacket(b, b.length,remoteAdress);
try {
sendsocket.send(sendpacket);
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
sendsocket.close();
text="";
}
else {}
///////////////////////////////////////////////////////
}
public static void main(String[] args) {
launch(args);
}
}
You code is really fuzzy, maybe I don't understand the purpose of all those code blocks but I can tell you UDP communication is pretty simple, let me first throw some quick light on way UDP communication works:
UDP communication refresher
Please note that I have used only some code snippets below for demonstration so kindly do not look then for completeness, complete code can be found in the code I have pasted in end.
UDP can be used for unicast as well as multicast communication. If UDP is used for unicast communication then there will always be a UDP client requesting something from a UDP server, however if UDP is used for multicast communication then UDP server will multicast/broadcast the message to all listening UDP clients.
(I will now talk more about UDP unicast) A UDP server will be listening on a network port for client requests DatagramSocket socket = new DatagramSocket(8002); socket.receive(packet);
A UDP client want to communicate with a UDP server, so it opens a DatagramSocket and send a DatagramPacket over it. DatagramPacket will contain the endpoints of the UDP server.
Once UDP client has sent the message using socket.send(packet);, it will then prepare to receive for the response from UDP server, using socket.receive(packet); (I think this where you are missing) Most important thing to understand is that if client doesn't prepare for receiving then it will not be able to get what UDP server would send because in case of UDP there is no connection between UDP client and UDP server, so UDP must be listening after sending the message.
UDP server will receive the request from UDP client, will process the request and will send using sendingDatagramSocket.send(packet);. It will prepare the DatagramPacket using the response and endpoints of the UDP client.
UDP client which is listening, as mentioned in above step socket.receive(packet); will get the response from UDP server. Important thing to note here is that if UDP client is not listening OR not listening on same port which it has opened while making the request (basically using the same DatagramSocket object used for sending the request) then UDP client will never receive whatever UDP server is going to send.
Answer to OP's questions
Main issue is that in Send_UDP you are only sending but not receiving and in recieve_UDP you are only receiving but not sending.
So, basically you need to both send and receive in UDP client and UDP server, its just that it would be vice-versa but you need to do both the things.
Sample UDP server and UDP client
UDP client:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
public class SimpleUDPClient {
public static void main(String[] args) throws IOException {
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
System.out.println("### socket.getLocalPort():" + socket.getLocalPort() + " | socket.getPort(): " + socket.getPort());
// send request
byte[] buf = "Hello, I am UDP client".getBytes();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 8002);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
System.out.println("Waiting to receive response from server." + new Date());
socket.receive(packet);
System.out.println("Got the response back from server." + new Date());
// display response
String received = new String(packet.getData());
System.out.println("Quote of the Moment: " + received);
socket.close();
}
}
UDP server:
import java.io.*;
import java.net.*;
import java.util.*;
public class SimpleUDPServer {
public static void main(String[] args) throws SocketException, InterruptedException {
DatagramSocket socket = new DatagramSocket(8002);
while (true) {
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("### socket.getLocalPort():" + socket.getLocalPort() + " | socket.getPort(): " + socket.getPort());
// figure out response
String dString = "Server is responding: asd asdd";
buf = new byte[256];
buf = dString.getBytes();
// send the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
System.out.println("Data from client: " + new String(packet.getData()));
packet = new DatagramPacket(dString.getBytes(), dString.getBytes().length, address, port);
System.out.println("### Sending for packet.hashCode(): " + packet.hashCode() + " | packet.getPort(): " + packet.getPort());
//Thread.sleep(5000);
System.out.println("Now sending the response back to UDP client.");
DatagramSocket sendingDatagramSocket = new DatagramSocket();
sendingDatagramSocket.send(packet);
sendingDatagramSocket.close();
System.out.println("I am done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Further readings
I strongly recommend read this Java tutorial, if not complete then at-least "Writing a Datagram Client and Server" section.

udp program not working

i tried my hands on networking and this is the first time i have understood some bit of it.i have a program with a client and server.What i want to do is that the server should send data continuously to a port and whenever there is any data in port say 2656 ,the client should read the data from that port and the data should be flushed from the port.I have created a server program and a client program but the client is not receiving any packet.I m running client and server on two different machines.
Server Program
import java.io.*;
import java.net.*;
public class Server{
public static void main(String args[]) throws Exception {
DatagramSocket dsocket = new DatagramSocket();
try {
String host = "192.168.0.15";
int count =1;
byte[] message = "Java Source and Support".getBytes();
// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// Initialize a datagram packet with data and address
for(;;)
{
DatagramPacket packet = new DatagramPacket(message, message.length,
address, 2656);
// Create a datagram socket, send the packet through it, //close it.
System.out.println("Sending data"+message.toString();
dsocket.send(packet);
}
} catch (Exception e) {
System.err.println(e);
}
finally
{
dsocket.close();
}
}
}
Client program
package saturdayTest;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceive {
public static void main(String args[]) {
try {
int port = 2656;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
System.out.println("Waiting for a packer");
dsocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
}
}
}

Is multithreading possible in a simple java server using udp connectionless protocol?

Is multi-threading possible in a simple java server using udp connectionless protocol? give an example!!
Multi-threading is actually simpler with UDP because you don't have to worry about connection state. Here is the listen loop from my server,
while(true){
try{
byte[] buf = new byte[2048];
DatagramPacket packet = new DatagramPacket( buf, buf.length, address );
socket.receive( packet );
threadPool.execute( new Request( this, socket, packet ));
.......
The threadPool is a ThreaPoolExecutor. Due to the short-lived nature of UDP sessions, thread pool is required to avoid the overhead of repeatedly thread creation.
Yes, it's possible through the use of the DatagramChannel class in java.nio. Here's a tutorial (It does not address the multithreading, but that is a separate issue anyway).
Here is one example try putting your own ip to get the hard-coded message back
package a.first;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Serv {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Listner listner = new Listner();
Thread thread = new Thread(listner);
thread.start();
String messageStr = "Hello msg1";
int server_port = 2425;
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("172.20.88.223");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local,
server_port);
System.out.println("about to send msg1");
s.send(p);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
messageStr = "Hello msg2";
msg_length = messageStr.length();
message = messageStr.getBytes();
p = new DatagramPacket(message, msg_length, local,
server_port);
System.out.println("about to send msg2");
s.send(p);
}
}
class Listner implements Runnable
{
#Override
public void run() {
String text = null;
while(true){
text = null;
int server_port = 2425;
byte[] message = new byte[1500];
DatagramPacket p = new DatagramPacket(message, message.length);
DatagramSocket s = null;
try{
s = new DatagramSocket(server_port);
}catch (SocketException e) {
e.printStackTrace();
System.out.println("Socket excep");
}
try {
s.receive(p);
}catch (IOException e) {
e.printStackTrace();
System.out.println("IO EXcept");
}
text = new String(message, 0, p.getLength());
System.out.println("message = "+text);
s.close();
}
}
}

Categories

Resources