I am a newbie in java networking , i made a client-server udp program. The server side is working fine but the client side is not receiving anything from server . Please correct the mistake.The server side is fully running but the client side is not working till its end . Any help would be great.
public class Client {
public static void main (String args[]) throws Exception {
DatagramSocket s = new DatagramSocket();
String msg = "Hello! ,from client. ";
byte[] b = msg.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(b, b.length, ia, 9999);
s.send(dp);
byte[] b2 = new byte[1024]; //byte array
DatagramPacket dip = new DatagramPacket(b2, b2.length);
s.receive(dip);
String str = new String(dip.getData());
System.out.println("From server" + str);
}
}
public class Server {
void run() throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(dp.getData());
System.out.println("Message from client:" + msg);
//giving back to client
String str = "HI!, from server.";
byte[] b2 = str.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, 9999);
ds.send(dop);
System.out.println("Message sent back");
ds.close();
}
public static void main(String args[]) throws Exception {
Server server = new Server();
server.run();
}
}
Your server is sending all responses to localhost, on port 9999. You need to update the server, so that it reads the address of the sender:
InetAddress ia = dp.getAddress();
int port = dp.getPort();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, port);
The error is your server and client run on the same host, so they must listen on different ports like below:
The server
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Server {
void run() throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(dp.getData(),0,dp.getLength(),"UTF-8");
System.out.println("Message from client:" + msg);
//giving back to client
String str = "HI!, from server.";
byte[] b2 = str.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, 9998);
ds.send(dop);
System.out.println("Message sent back");
ds.close();
}
public static void main(String args[]) throws Exception {
Server server = new Server();
server.run();
}
}
and the client
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main (String args[]) throws Exception {
DatagramSocket s = new DatagramSocket(9998);
String msg = "Hello! ,from client. ";
byte[] b = msg.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(b, b.length, ia, 9999);
s.send(dp);
byte[] b2 = new byte[1024]; //byte array
DatagramPacket dip = new DatagramPacket(b2, b2.length);
s.receive(dip);
String str = new String(dip.getData(),0,dip.getLength(),"UTF-8");
System.out.println("From server" + str);
}
}
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.
The task is to
(1) Send message from Client to Server via Bridge
(2) Send back the message in UPPER CASE from server to client via Bridge
(1) is done
I am have problem with sending the message back to the client
Here are the classes:
UDPCLIENT
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
//getting input from the user and sending to Bridge
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 4000);
clientSocket.send(sendPacket);
//Getting data from the Bridge
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("C: FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
UDPSERVER
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(5000);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
//receiveing data from the bridge
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("S:RECEIVED: " + sentence);
InetAddress IPAddress = InetAddress.getByName("localhost");
// Sending data to the bridge
int port = 4000;
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Bridge
import java.io.*;
import java.net.*;
/**
* Write a description of class Bridge here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Bridge
{
public static void main(String args[]) throws Exception{
DatagramSocket bridgeSocket1 = new DatagramSocket(4000);
DatagramSocket bridgeSocket2 = new DatagramSocket();
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramPacket receivePacket;
DatagramPacket sendPacket;
InetAddress IPAddress = InetAddress.getByName("localhost");
while(true){
//Receiveing data from the UDPClient
receivePacket = new DatagramPacket(receiveData, receiveData.length);
bridgeSocket1.receive(receivePacket);
//Sending data to UDPServer
String sentence = new String(receivePacket.getData());
System.out.println("B: Data Received:" + sentence);
int port = 5000;
sendData = sentence.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
bridgeSocket2.send(sendPacket);
// Receiving Data from the UDPServer
receivePacket = new DatagramPacket(receiveData,receiveData.length);
bridgeSocket1.receive(receivePacket);
String capitalizedSentence = new String(receivePacket.getData());
System.out.println("Capitalized Sentence in the Bridge Class: " + capitalizedSentence);
//Sending data to the UDPClient
sendData = capitalizedSentence.getBytes();
sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,5000);
bridgeSocket2.send(sendPacket);
}
}
}
You are sending the response from the server back to the server because you are using port 5000 as the destination port. But the server is running on 5000, not your client. You have to assign your client to a port as well and send the message received from the server back to the client on the defined port.
For now your sequence looks like this:
(C) ---> 4000
---> 5000
4000 <---
---> 5000
4000 <---
---> 5000
4000 <---
---> 5000
4000 <---
[...]
But it should look like this:
(C) ---> 4000
---> 5000
4000 <---
4500 <---
(assuming your client is listening on port 4500)
I'm trying to send some data by UDP. This is my code:
public class UDP {
public static void main(String args[]) throws IOException {
InetAddress inetAddress = InetAddress.getByName("239.255.42.99");
int PORT = 2225;
int BUFFER_SIZE = 10;
DatagramSocket datagramSocket = new DatagramSocket(PORT, inetAddress);
byte[] buf = new byte[BUFFER_SIZE];
String message = "0123456789";
buf = message.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
datagramPacket = new DatagramPacket(buf, buf.length);
datagramPacket.setAddress(inetAddress);
datagramPacket.setPort(PORT);
datagramSocket.send(datagramPacket);
datagramSocket.setSoTimeout(1010);
}
}
I have this error:
Exception in thread "main" java.io.IOException: Invalid argument
at java.net.PlainDatagramSocketImpl.send(Native Method)
at java.net.DatagramSocket.send(DatagramSocket.java:698)
at UDP.main(UDP.java:21)
Anyone know what I do wrong?
Try it this way:
public static void main(String args[]) throws IOException {
InetAddress inetAddress = InetAddress.getByName("239.255.42.99");
int PORT = 2225;
int BUFFER_SIZE = 10;
DatagramSocket datagramSocket = new DatagramSocket();
byte[] buf = new byte[BUFFER_SIZE];
String message = "0123456789";
buf = message.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, inetAddress, PORT);
datagramSocket.send(datagramPacket);
datagramSocket.setSoTimeout(1010);
}
I wrote this code to recive data from a client via socket
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(12890);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
But if I try to launch another Client it don't work , look like if the server is blocked. How can I change the code to let the server communicating with more then one client
You are looking for a concurrent server. A concurrent server basically creates a child process for each client. Here is a basic way to do in java http://www.how2java.com/2012/05/how-to-create-concurrent-server-using.html
I have made a program to send an UDP packets from a client to a server.
Here is the transmitter code:
import java.io.IOException;
import java.net.*;
public class JavaApplication9 {
public static void main(String[] args) throws UnknownHostException, SocketException, IOException {
// TODO code application logic here
byte[] buffer = {10,23,12,31,43,32,24};
byte [] IP = {-64,-88,1,106};
InetAddress address = InetAddress.getByAddress(IP);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, address, 57
);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
System.out.println(InetAddress.getLocalHost().getHostAddress());
}
}
The receiver code function is this:
public void run() {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
byte[] sendData = new byte[8];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String sendString = "polo";
sendData = sendString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
I have used the Wireshark program. The UDP packet is received in the Wireshark program at the receiver but the Java program wouldn't recognize it, the program just keeps listening to the port and nothing happens?
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging, try listening on port > 1024 (e.g. 5000 or 9000). Ports < 1024 are normally used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check to prevent such a situation.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}