I've been working on different ways to do this for 2 full coding days, i need some help:
I want to create a multiplayer game in java online. To do this i need communication between the server and the applet
I was under the impression that as long as the UDP server is being ran on the same machine the applet is being hosted on, it would work. (perhaps i need to be corrected on that)
I continually get this error on the error console (from applet)
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:5556 connect,resolve)
When trying to receive messages on the applet, nothing happens, nothing is sent and nothing is received (the udp server is sending a message,applet is not receiving, i know the udp is sending correctly as i tested separately it with a client)
Here is the UDPclient.java applet:
``
import java.io.*;
import java.net.*;
import java.applet.*;
public class UDPClient extends Applet
{
protected DatagramSocket socket = null;
protected DatagramPacket packet = null;
String ipAddress;
public void init()
{
try{
System.out.println("got username");
String username = getParameter("username");
System.out.println("got ip");
ipAddress = getParameter("ip");
System.out.println("makingsocket");
socket = new DatagramSocket();
System.out.println("sending packet");
sendPacket();
System.out.println("receiving packet");
receivePacket();
System.out.println("closing socket");
socket.close();
}catch(Exception e){e.printStackTrace();}
}
public void sendPacket() throws IOException
{
byte[] buf ="hihihi".getBytes(); // send hihihi
InetAddress address = InetAddress.getByName(ipAddress);
packet = new DatagramPacket(buf, buf.length, address, 5556);
System.out.println("sending packet");
socket.send(packet);
int port = packet.getPort();
}
public void receivePacket() throws IOException
{
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
System.out.println("getting packet--- calling socket.receive");
socket.receive(packet);
System.out.println("got here, receiving packet");
String modifiedSentence =new String(packet.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
}
}
Here is the HTML file i run the applet with:
<applet code="UDPClient.class" width="640" height="480">
<param name="username" value="Guest">
<param name="ip" value="localhost">
</applet>
And here is the server i'm using
import java.io.*;
import java.net.*;
public class multiTest
{
static protected DatagramSocket socket = null;
static protected DatagramPacket packet = null;
public static void main(String [] args) throws IOException
{
socket = new DatagramSocket(5556);
while(true)
{
receivePacket();
sendPacket();
}
}
public static void receivePacket() throws IOException
{
//receive message from client
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
//translate message in a thread
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("received" + message);
// should really make thread;
}
public static void sendPacket() throws IOException
{
byte[] buf = "ack".getBytes();
//send the message to the client to the given address and port
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
}
}
I have been trying to follow the tutorial here :http://corvstudios.com/tutorials/udpMultiplayer.php to create this code.
i really didnt wanna have to end up using MINA, Tomcat or install any network framework - but if i have to let me know, it'll save me a lot of time
Any help is sincerely appreciated in advanced!
The JRE used by your applet need to be configured to authorize access thé file system to your applet. See policy or security for applet
Related
I am doing a server and client socket datagram.
The client connects to the server and you need to write in the client a string that contains Hello or hello.
When the server detects a string with hello or Hello, repplies to the client with another string.
The problem is that the client doesn't read the string that the server sends.
Here is my code.
Client
public class Client {
public static void main(String[] args) {
try {
System.out.println("Creando socket datagram");
DatagramSocket datagramSocket = new DatagramSocket();
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Say Hello");
String saludo = myObj.nextLine();
System.out.println("Sending message");
InetAddress addr = InetAddress.getByName("localhost");
DatagramPacket datagrama = new DatagramPacket(saludo.getBytes(), saludo.getBytes().length, addr, 5555);
datagramSocket.send(datagrama);
System.out.println("Message sent");
System.out.println("Reading message");
byte[] mensaje = new byte[25];
DatagramPacket datagrama1 = new DatagramPacket(mensaje, 25);
datagramSocket.receive(datagrama1);
System.out.println("Message recieved: " + new String(mensaje));
System.out.println("Closing");
datagramSocket.close();
System.out.println("FInished");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
public class Server {
public static void main(String[] args) throws InterruptedException {
try {
for (;;) {
System.out.println("Creating socket datagram");
InetSocketAddress addr = new InetSocketAddress("localhost", 5555);
DatagramSocket datagramSocket = new DatagramSocket(addr);
System.out.println("RReading message");
byte[] mensaje = new byte[25];
DatagramPacket datagrama1 = new DatagramPacket(mensaje, 25);
datagramSocket.receive(datagrama1);
System.out.println("Message recieved: " + new String(mensaje));
if (new String(mensaje).contains("hello") || new String(mensaje).contains("Hello")) {
String quetal = "¿Hello, how are you doing?";
System.out.println("Sending message");
TimeUnit.SECONDS.sleep(2);
DatagramPacket datagrama2 = new DatagramPacket(quetal.getBytes(), quetal.getBytes().length, addr.getAddress(),
5555);
datagramSocket.send(datagrama2);
System.out.println("Message Sent");
}
datagramSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have tried putting a sleep in the server in case the server sends the string before the client tries to read.
Many thanks for the help as always.
The client is using the parameter-less DatagramSocket() constructor to bind to a random port with which to send and receive on:
Constructs a datagram socket and binds it to any available port on the local host machine. The socket will be bound to the wildcard address, an IP address chosen by the kernel.
However, when the server receives a datagram, you are ignoring the IP and port where the datagram was actually sent from:
DatagramSocket.receive(DatagramPacket)
Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine.
When the server is sending the reply, you are sending it back to the server itself at localhost:5555, not to the client at all.
On the server side, you need to change this:
DatagramPacket datagrama2 = new DatagramPacket(..., addr.getAddress(), 5555);
To either this:
DatagramPacket datagrama2 = new DatagramPacket(..., datagrama1.getAddress(), datagrama1.getPort());
Or to this:
DatagramPacket datagrama2 = new DatagramPacket(..., datagrama1.getSocketAddress());
On a side note, your server is also ignoring the actual length of the data that is being sent by the client. The server is receiving data using a 25-byte array, but the client may not actually be sending 25 bytes. If the client sends less than 25 bytes, you will end up with a String that contains random garbage on the end of it. And if the client sends more than 25 bytes, `receive() will truncate the data.
Try something more like this instead:
System.out.println("Reading message");
byte[] buffer = new byte[65535];
DatagramPacket datagrama1 = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(datagrama1);
String mensaje = new String(datagrama1.getData(), datagrama1.getLength());
System.out.println("Message recieved: " + mensaje);
if (mensaje.contains("hello") || mensaje.contains("Hello")) {
...
}
This was fun :)
Kindly keep in mind, the way this is coded might not be the best, however it works as you want.
The Client sends Hello, The server receives Hello, and Sends (Hello back at you).
Both then terminate. It doesnt keep on looping those 2 messages forever, but I showed you the idea.
The Server needs to act as a Client as well in order to send messages.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class DReceiver{
public static void replyToTheClientListening() throws IOException {
DatagramSocket ds = new DatagramSocket();
String str = "hello back at you";
InetAddress ia = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ia, 3001);
ds.send(dp);
ds.close();
}
public static void listenToMessagesFromTheClient() throws IOException {
DatagramSocket ds = new DatagramSocket(3000);
ds.setSoTimeout(60000); //Wait 60 SECONDS for messages
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String strRecv = new String(dp.getData(), 0, dp.getLength());
if("hello".equalsIgnoreCase(strRecv)) { //hello in any case
System.out.println("Received a MSG from the Client " + strRecv);
replyToTheClientListening();
}
ds.close();
}
public static void main(String[] args) throws Exception {
listenToMessagesFromTheClient();
}
}
The DSender is a Client but also needs to act as a Server (To Listen to Messages coming in from the other Server)
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class DSender{
public static void actAsAServerAndListenToMessages() throws IOException {
//Listen to Port 3001 --The Server will send to that port
DatagramSocket dsReceive = new DatagramSocket(3001);
dsReceive.setSoTimeout(60000); //Make it wait 60 SECONDS
byte[] buf = new byte[1024];
DatagramPacket dpReceive = new DatagramPacket(buf, 1024);
dsReceive.receive(dpReceive);
String strRecv = new String(dpReceive.getData(), 0, dpReceive.getLength());
System.out.println("Client -- Received a Msg back from Server --" + strRecv);
dsReceive.close();
}
public static void sendAMessageAsAClientToTheServer() throws IOException {
// Client will send a message to Port 3000 which the Server listens to.
DatagramSocket ds = new DatagramSocket();
String str = "hello";
InetAddress ia = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ia, 3000);
ds.send(dp);
ds.close();
}
public static void main(String[] args) throws Exception {
sendAMessageAsAClientToTheServer();
actAsAServerAndListenToMessages();
}
}
Reference :
https://www.javatpoint.com/DatagramSocket-and-DatagramPacket
I run the server, then the Client.
Am new to Socket programming am trying to establish a communication between a Server and a client but i don't know how to do that am a bit confused on how to go about it. I have written the program below but it is given error and i can't get my head round why.
package server;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Server {
public static void main(String[] args) {
// TODO code application logic here
try {
DatagramSocket socket = new DatagramSocket(7000);
socket.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
String message = new String (buffer);
System.out.println(message);
String Reply ="Am here";
DatagramPacket data = new DatagramPacket(Reply.getBytes(), Reply.getBytes().length, packet.getAddress(), packet.getPort());
socket.send(data);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
Client
package client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) {
// TODO code application logic here
try{
String message = "Hello Server";
String host = "localhost";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 7000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
DatagramSocket sockets = new DatagramSocket(7000);
sockets.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packets = new DatagramPacket(buffer,buffer.length);
sockets.receive(packets);
String messages = new String (buffer);
System.out.println(messages);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
How can i get them communicated. I have heard about Multi-threading but can't get my head round how it works.
I get the following error.
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagramSocketImpl.java:84)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:93)
at java.net.DatagramSocket.bind(DatagramSocket.java:392)
at java.net.DatagramSocket.<init>(DatagramSocket.java:242)
at java.net.DatagramSocket.<init>(DatagramSocket.java:299)
at java.net.DatagramSocket.<init>(DatagramSocket.java:271)
at client.Client.main(Client.java:32)
If you wanting to send/receive from a client to a server using a socket then use ServerSocket on the serverside.
Then use accept - This listens for a connection to be made to this socket and accepts it.
The Socket object returned by Accept has Input and Output Stream which can be be read and written to.
The client will just use a Socket Object
See http://cs.lmu.edu/~ray/notes/javanetexamples/ for an example
If for some reason you insist on using DatagramSocket, then see this example https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
The error occurs because the port you are trying to bind your socket to is already in use. Port 7000 is used both by the client and server:
DatagramSocket sockets = new DatagramSocket(7000);
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.
I have multiple transmitters configured to send back a response when they receive a broadcast packet sent from a server through local port 5255, remote port 5252 containing the string "AST show me\0" (as stated in transmitters' manual). This should help me to scan for all the transmitters within the local network.
I have implemented a server side code to broadcast that string message, but when I run the code , it have a bug at the following line code :
socket.receive(packet1);
I don't really know what I am doing wrong or missing in this code.
Any help will be greatly appreciated.
Note: If it might help : The transmitters' IP address are from 192.168.40.* ; and the server IP address is 192.168.40.254.
Thanks in advance !!
Here is the code :
package socket_test;
import java.io.*;
import java.net.*;
public class Server_UDP_Broadcast {
//#SuppressWarnings("null")
public static void main(String[] args) {
// TODO Auto-generated method stub
DatagramSocket socket = null;
try{
socket = new DatagramSocket(5255);
socket.setSoTimeout(10000);
String str = "AST show me\0";
byte[] buf = new byte[256];
buf = str.getBytes();
InetAddress group = InetAddress.getByName("255.255.255.255");
DatagramPacket packet;
packet = new DatagramPacket(buf, buf.length, group, 5252);
socket.send(packet);
// receive answer and display
byte[] buf1 = new byte[1024];
DatagramPacket packet1 = new DatagramPacket(buf1, buf1.length);
socket.receive(packet1);
String received = new String(packet1.getData(), 0, packet1.getLength());
System.out.println("Answer from I-Lite :: " + received);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Here are the bugs :
java.net.SocketTimeoutException: Receive timed out
at java.net.DualStackPlainDatagramSocketImpl.socketReceiveOrPeekData (Native Method)
at java.net.DualStackPlainDatagramSocketImpl.receive0(Unknown Source)
at java.net.AbstractPlainDatagramSocketImpl.receive(Unknown Source)
at java.net.DatagramSocket.receive(Unknown Source)
at socket_test.Server_UDP_Broadcast.main(Server_UDP_Broadcast.java:31)
Here is the screenshots from from wireshark:
Captured packet's details
WireShark's Screenhot
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);
}
}
}