I'm try use my IOT device with Java, but the Java doesn't receive any UDP packet. My packets are very simple and I belive that this is the problem.
The wireshark listen all the packets and a similar DELPHI software too.
My code:
package br.imply.server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
public static void main(String[] args) {
try {
int porta = 4865;
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramSocket serverSocket = new DatagramSocket(porta);
boolean isStopped = false;
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("Iniciando servidor: " + inetAddress.getHostAddress() + ":" + porta);
while (!isStopped) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("Aguardando conexão...");
serverSocket.receive(receivePacket);
System.out.println("Conectado em " + receivePacket.getAddress());
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);
//do something with clientSocket
}
} catch (IOException ex) {
System.out.println(Main.class.getName() + " " + ex);
}
}
}
Related
I need to write a Java program that can catch UDP packets. I wrote a basic UDP Receiver program but I am unsure how to adjust it for this purpose.
import java.io.*;
import java.net.*;
public class BasicReceiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new BasicReceiver().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
InetAddress IPAddress = receivePacket.getAddress();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
I am not receiving any packets but I can see packets on my Ethernet Port:
WireShark Snapshot
I want to create a datagram server/client program where the server picks a random string from an array and send it to the client. But when i run the server and then the client which sends data about the buf byte array. The client sends the data to the serve as I understand but the server doesn't receive it.
Here's the client code:
import java.io.*;
import java.net.*;
import java.util.*;
public class SDClient {
protected static String labelText;
public static void main(String[] args) throws IOException {
//socket setup
MulticastSocket socket = new MulticastSocket(1);
System.out.println("socket opened");
InetAddress group = InetAddress.getByName("230.0.0.0");
socket.joinGroup(group);
System.out.println("socket joined group");
//packet setup
DatagramPacket packet;
byte[] buf = new byte[256];
//send packet
packet = new DatagramPacket(buf, buf.length);
packet.setAddress(group);
packet.setPort(2);
socket.send(packet);
System.out.println("packet sent to: ");
System.out.println("Port: " + packet.getPort() + " Address: " + packet.getAddress());
//receive packet
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("packet received");
//display packet string
labelText = new String(packet.getData(), 0, packet.getLength());
System.out.println("label text: " + labelText);
socket.leaveGroup(group);
socket.close();
}
}
here's the server code:
import java.io.*;
import java.net.*;
import java.util.*;
public class SDServerThread extends Thread {
protected DatagramSocket socket = null;
protected String[] labelText = {"Packet sent and received", "Hello World!", "It works."};
public SDServerThread() throws IOException {
this("SDServerThread");
}
public SDServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(2);
System.out.println("socket opened");
}
public void run() {
try {
byte[] buf = new byte[256];
DatagramPacket packet = null;
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("packet received");
String getText = getText();
buf = getText.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.0");
packet = new DatagramPacket(buf, buf.length, group, 1);
socket.send(packet);
System.out.println("packet sent");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getText() {
int textNr = (int)(Math.random() * 3);
String returnT = labelText[textNr];
return returnT;
}
}
Thanks in advence
I fixed it by making the servers DatagramSocket into a MulticastSocket and then made it join the group the client is in.
public class SDServerThread extends Thread {
protected MulticastSocket socket = null;
...
socket = new MulticastSocket(2);
...
socket.joinGroup(group);
}
I have the following UDP client and servcer classes and I am trying to send some string from the UDPClient to the another class 'UDPServer' in the same java project at the localhost and port 7777. I am facing problem that I am not receiving anything in the UDPServer class from the UDPClient class. Does anyone have an idea where the problem is?
I appreciate any help!
UDPClient
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class UDPClient {
public static void main(String args[]) throws Exception {
String aString = "Hello World";
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = aString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
UDPServer
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(7777);
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);
}
}
}
Hi try to check what wrong with port allocation, because you code works ok.
Start your server and run this command:
Windows
netstat -aon | FINDSTR 7777
Linux:
netstat -aon | grep 7777
You should see the PID check if pid is same as UDPServer runs on. Also check firewall maybe there is something wrong?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
GreetingClient code:
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
GreetingServer code
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(6000000);
}
public void run(){
while(true){
try{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "+ server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}
catch(SocketTimeoutException s){
System.out.println("Socket timed out!");
break;
}
catch(IOException e){
e.printStackTrace();
break;
}
}
}
public static void main(String [] args){
int port = Integer.parseInt(args[0]);
try{
Thread t = new GreetingServer(port);
t.start();
}
catch(IOException e){
e.printStackTrace();
}
}
}
//here is the code i want to insert in the client part. this code lets the user type a string (that i want to let it appear on the server side) and asks the user if he want to communicate with the server again.
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class com {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = null;
Scanner sc =new Scanner(System.in);
boolean yes = true;
do{
System.out.println("What do you want to say to the server?");
String toServer = sc.nextLine();
System.out.println ("The client said: " + toServer);
System.out.println("Do you wish to continue(y/n)?");
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(s.equals("n")){
yes=false;
}
}
while (yes== true);
}
}
the code works perfectly but not as i want.first i want to include to include the above code(before the last comments) in the greeting user. i want to make a client server communication. i have copied and pasted the GreetingServer and GreetingClient part. but once the connection is established between the client and server, the Strings from the GreetingServer and GreetingClient codes appear. that is not what i want. i want to output the user's input from the GreetingClient to the GreetingServer.
the user's input: hi server
On the server should appear : hi server
Here's a UDP example for you to follow. Should be simple to implement the same approach in your own code.
UdpServer
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpServer {
private static final int SERVER_PORT = 9876;
public static void main(String args[]) {
try {
DatagramSocket serverSocket = new DatagramSocket(SERVER_PORT);
while(true) {
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String input = new String(receivePacket.getData());
input = input.trim();
System.out.println("RECEIVED: " + input);
InetAddress ipAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedInput = input.toUpperCase();
sendData = capitalizedInput.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);
serverSocket.send(sendPacket);
Thread.sleep(50);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
UdpClient
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClient {
private static final String CLIENT_IP = "localhost";
private static final int CLIENT_PORT = 9876;
public static void main(String args[]) {
try {
while (true) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress ipAddress = InetAddress.getByName(CLIENT_IP);
String input = bufferedReader.readLine();
byte[] sendData = input.getBytes();
byte[] receiveData = new byte[1024];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, CLIENT_PORT);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedInput = new String(receivePacket.getData());
modifiedInput = modifiedInput.trim();
System.out.println("FROM SERVER:" + modifiedInput);
clientSocket.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I took code from some sources in internet, here it is:
Server Side:
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
serverSocket.setBroadcast(true);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
//System.out.println(serverSocket.getAddress().getHostAddress());
System.out.println(receivePacket.getAddress().getHostAddress()+" is connected");
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("RECEIVED: " + sentence +" from: "+receivePacket.getAddress().getHostAddress());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("Port: "+port);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, port); //
serverSocket.send(sendPacket);
}
}
}
Client1 Side:
import java.io.*;
import java.net.*;
class Client1 {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
clientSocket.setBroadcast(true);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
Boolean status = true;
while(status){
String sentence = "";
sentence = inFromUser.readLine();
if(sentence.equals("exit")){
break;
}
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("FROM SERVER:" + modifiedSentence);
}
clientSocket.close();
}
}
Client2 Side: same as Client1.
My questions are:
how to give notification in Server side which will tell you the client's IP address when a client is connected?
how to broadcast message from one client to the other clients? ex: Client1 sends message to Server, the Server broadcast the message to all of its clients, not only to Client1.
Thank you in advance