Datagramsocket is not receiving - java

Hello everyone I am very new to java, I am trying datagramsocket send and receive packets. My client is sending packets, but server is not receiving.
Please help me, Thanks in advance.
My client side code is as follows:
outString = "Hello World"
InetAddress hostAddress = InetAddress.getByName("localhost");
buf = outString.getBytes();
DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 4002);
s.send(out);
My server side code is :
DatagramSocket sk = new DatagramSocket(PORT);
DatagramPacket dgp = new DatagramPacket(buf, buf.length);
sk = new DatagramSocket(PORT); //PORT is 4002
while (true) {
sk.receive(dgp);
String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
+ dgp.getAddress() + ", port: " + dgp.getPort();
System.out.println(rcvd);
}

This example works for me
public static void main(String[] args) throws IOException {
if (args.length == 0) {
byte[] buf = new byte[128];
DatagramPacket dgp = new DatagramPacket(buf, buf.length);
DatagramSocket sk = new DatagramSocket(PORT); //PORT is 4002
while (true) {
sk.receive(dgp);
String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
+ dgp.getAddress() + ", port: " + dgp.getPort();
System.out.println(rcvd);
}
} else {
String outString = "Hello World";
InetAddress hostAddress = InetAddress.getByName("localhost");
byte[] buf = outString.getBytes();
DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 4002);
DatagramSocket s = new DatagramSocket();
s.send(out);
}
}

Related

Enable to ping from different machine

I have created 2 java programs, client pings the server and the server reply to client. The problem that I'm having is that the programs works fine when I tried to run both client and server on the same machine. But when I tried to run the client and the server separately (that is the client and servers on another machine in virtualbox) I'm getting no response from the server. Any help ?
Function for the client to send ping request
public static void ping(String serverIP, int numberOfPacketToSend,int setTimeOut,int sendDa){
int lossPacket = 0;
try {
String serverHostname = new String (serverIP);
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("connecting to " + IPAddress+"...");
byte[] sendData = new byte[sendDa];
byte[] receiveData = new byte[sendDa];
for(int i = 0;i<numberOfPacketToSend;i++){
String sentence = "Pinging "+serverIP;
//sendData = sentence.getBytes();
// System.out.println ("Sending data to " + sendData.length +
// " bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
//System.out.println("data being send to server "+sendData.length);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
// System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(setTimeOut);
try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
// System.out.println ("From server at: " + returnIPAddress +
// ":" + port);
System.out.println("Reply from "+serverIP+" bytes="+sendData.length);
}
catch (SocketTimeoutException ste)
{
System.out.println ("Timeout Occurred: Packet assumed lost");
lossPacket ++;
}}
clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
System.out.println("Total loss packet = "+lossPacket);
System.out.println("Number of packet send ="+numberOfPacketToSend);
try{
System.out.println("Percentage packet loss ="+((numberOfPacketToSend/lossPacket)*100)+"%");
}catch(ArithmeticException e){System.out.println("Percentage packet loss = 0%");}
}
}
function for the server to wait for any connections
public static void waitForConnection(int portNumber, String ServerAddress) throws IOException{
try
{
InetAddress addr = InetAddress.getByName("5.5.5.5");
DatagramSocket serverSocket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress(ServerAddress, portNumber);
serverSocket.bind(address);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
receiveData = new byte[1024];
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Server up and running on port "+portNumber);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From: " + IPAddress + ":" + port);
System.out.println ("Message: " + sentence);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
catch (SocketException ex) {
System.out.println("UDP Port 9876 is occupied.");
System.exit(1);
}
}

Connect to MD110 pbx using c# Socket Programming

I am trying to login Ericsson MD110 alex through the c# application. The md110 returned values that asking the username for login the application, but once I pass the username and password through the following code:
public static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
string stringData;
//TcpClient tcpclnt = new TcpClient();
//Console.WriteLine("Connecting.....");
string ipaddress = "192.168.1.30";
int port=23;
IPAddress ipadd = IPAddress.Parse(ipaddress);
IPEndPoint ipend = new IPEndPoint(ipadd, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = false;
sock.Connect(ipend);
//recive data
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
Console.Write(stringData);
//while (true)
//{
Byte[] bBuf;
string buf;
//Application.DoEvents();
//buf = String.Format("{0}\r\n{1}\r\n", "MDUSER", "HELP");
buf = String.Format("ALREI;");
//buf = string.Format("ENTER USER NAME<.MDUSER;MDUSER;ENTER PASSWORD<.HELP;");
bBuf = Encoding.ASCII.GetBytes(buf);
sock.Send(bBuf);
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
string df = "";
Console.Write(stringData);
Console.ReadLine();
//}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadKey();
}
}
Further, I checked with wireshark, but md110 doesn't return any value.
only acknowledge data packet will receive.
I need some advice.

How to check if the sent message is the same as the received message in a simple UDP server

Here's the simple UDP server I'm talking about.
How can we check if the string we send through the client is the same as the one received? I have tried a simple if condition to check if they are equal, using the equal() method of strings but even though the messages are the same the if condition results false, even when comparing the sent and received messages using the .toString() method.
import java.net.*;
import java.io.*;
import java.util.Arrays;
public class UDPClient {
public static void main(String args[]) throws Exception
{
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, 7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String sentSentence = new String(sendPacket.getData());
String receivedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + receivedSentence + "\n" + "IP Address: " + receivePacket.getAddress() + "\n" +
"Message Size: " + receivePacket.getData().length);
clientSocket.close();
System.out.println(sentSentence + " " + receivedSentence);
if(sentSentence.equals(receivedSentence.toString()))
System.out.println("OK" + " " + sentence + " " + receivedSentence);
else
System.out.println("FAILED");
}
}
String sentSentence = new String(sendPacket.getData());
String receivedSentence = new String(receivePacket.getData());
As expected, you aren't constructing these Strings correctly. It should be:
String sentSentence = new String(sendPacket.getData(), sendPacket.getOffset(), sendPacket.getLength());
String receivedSentence = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());

UDP Client/Server object transfer help

I'm trying to transfer an ArrayList from a client to a server using the UDP protocol.
The transfer starts at the "max" if statement.
Same in the server side
This is the client:
public class UdpClient {
protected DatagramPacket sendPacket;
protected DatagramPacket receivePacket;
public static void main(String args[]) throws IOException,
ClassNotFoundException {
UdpClient upd = new UdpClient();
ArrayList<Integer> arr = new ArrayList<Integer>();
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutput oo = new ObjectOutputStream(bStream);
ByteArrayInputStream baos;
ObjectInputStream oos;
System.out
.println("Commands: Time, Date, Weather, Sum-number, Max-number, Exit");
while (true) {
String fromUsr = inFromUser.readLine();
if (fromUsr.equals("bye")) {
break;
} else if (fromUsr.equals("weather")) {
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
System.out
.println("Please select a ctiy: Lund, Malmo, Stockholm");
String weather = inFromUser.readLine();
sendData = weather.getBytes();
upd.sendPacket(sendData, clientSocket);
upd.receivePacket(clientSocket, receiveData);
} else if (fromUsr.equals("max")) {
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
String max = inFromUser.readLine().trim();
upd.nums(max, arr);
oo.writeObject(arr);
byte[] buf = new byte[bStream.toByteArray().length];
buf = bStream.toByteArray();
upd.sendPacket(buf, clientSocket);
System.out.println(arr);
} else {
// send data that of the user
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
upd.receivePacket(clientSocket, receiveData);
}
String fromServer = new String(upd.getData());
System.out.println("Message from server:\n" + fromServer);
}
}
private void sendPacket(byte[] sendData, DatagramSocket clientSocket)
throws IOException {
InetAddress IPAddress = InetAddress.getByName("ericman-PC");
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9876);
clientSocket.send(sendPacket);
}
private void receivePacket(DatagramSocket serverSocket, byte[] receiveData)
throws IOException {
byte[] rData = new byte[1024];
receiveData = rData;
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
}
This is the Server
public class UdpServer {
protected DatagramPacket receivePacket;
protected DatagramPacket sendPacket;
public static void main(String args[]) throws IOException,
ClassNotFoundException {
UdpServer upd = new UdpServer();
DatagramSocket serverSocket = new DatagramSocket(9876);
DateFormat currentDate = new SimpleDateFormat("yyyy/MM/dd");
DateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
ByteArrayInputStream baos;
ObjectInputStream oos;
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true) {
System.out.println("****************************************"
+ "\nServer is connected");
upd.receivePacket(serverSocket, receiveData);
String str = new String(upd.getData()).trim();
System.out.println("Message received is:" + " " + str);
if (str.equals("time")) {
str = currentTime.format(date);
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("date")) {
str = currentDate.format(date);
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("weather")) {
upd.receivePacket(serverSocket, receiveData);
str = upd.weather(str = new String(upd.getData()).trim());
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("max")) {
byte[] buf = new byte[1024];
System.out.println("waitng for object to come");
upd.receivePacket(serverSocket, buf);
baos = new ByteArrayInputStream(buf);
oos = new ObjectInputStream(baos);
Object o = oos.readObject();
System.out.println(o);
} else {
str = "Unknown command, please try again..";
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
}
}
}
This is the error i get in the Server side
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at UdpServer.main(UdpServer.java:54)
Line 54 that the error indicates is this line on the server
baos = new ByteArrayInputStream(buf);
oos = new ObjectInputStream(baos);
If you could help me out of why this error is happening? thanx!
Your code creates alot of arrays it immediately discards. I would use a debugger to step through the code so you understand what it is doing.
private void receivePacket(DatagramSocket serverSocket, byte[] receiveData)
throws IOException {
// create a new array
byte[] rData = new byte[1024];
// throw away the orignal array so the new array will be update.
receiveData = rData;
// copy into the new array, not the old one.
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
}
In this case, the original receiveData will not me modified so it will contain lots of 0 bytes.
byte[] buf = new byte[bStream.toByteArray().length];
buf = bStream.toByteArray();
This creates three arrays when all you need is one. The first array bStream.toByteArray() is created just so you can determine what length it would be. You create a second array which is the same length but empty and put it in buf Finally you discard the second array and replace it with a copy of the first array.

UDP threading infinite loop in Java

I've written two programs. Now each program uses threading to send and receive packets at the same time.
Whenever I send packets from the server to the client, the message at the client ends gets received in an infinite loop. I.e; I've added a print statement that prints the message sent and this goes forever in an infinite loop. I want to make it so that it receives the message, and then be able to write back to the server and exit whenever the user wants to.
I've tried using socket.close(), but this makes it so that the client receives the message and I can only write back to the server once. After I send it, I can't send anymore. I want to make it so that I can write back more than once.
Can anyone please point me in the right direction?
My code is as follows;
public class UDPThreadClient extends Thread {
public static int port1;
//Create threaded server
UDPThreadClient (int port1) {
System.out.println ("Starting threaded client");
start();
}
public void run() {
int port = port1;
try {
DatagramSocket serverSocket = new DatagramSocket(port1);
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());
SocketAddress address = receivePacket.getSocketAddress();
System.out.println("RECEIVED from " + address + " : " + 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);
//serverSocket.close();
}
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
//Create client
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
port1 = Integer.parseInt(args[1]);
new UDPThreadClient (port1);
try {
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, port);
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();
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
}
and
public class UDPThreadServer extends Thread {
public static int port1;
//Create threaded client
UDPThreadServer () {
System.out.println ("Starting threaded server");
start();
}
public void run() {
try {
DatagramSocket clientSocket = new DatagramSocket();
BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
Scanner in = new Scanner (inFromUser);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte [1024];
byte[] receiveData = new byte [1024];
while (in.hasNextLine()) {
String sentence = in.nextLine();
//inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port1);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length);
clientSocket.receive (receivePacket);
String modSentence = new String (receivePacket.getData());
System.out.println ("FROM SERVER: " + modSentence);
}
//clientSocket.close();
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
//Create server
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
port1 = Integer.parseInt(args[1]);
new UDPThreadServer ();
try {
DatagramSocket serverSocket = new DatagramSocket (port);
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());
SocketAddress address = receivePacket.getSocketAddress();
System.out.println ("Received from " + address + " : " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String capSentence = sentence.toUpperCase();
sendData = capSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
//serverSocket.close();
}
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
}
Thanks.
Looking at UDPClientServer:
When you create the Datagram packet, you give it the port to send it to, not the port that you are sending it from.
When I ran your code, nothing happened. The server is waiting on port port, while the client sends to port port1. If you instead send to port port (not accessible from the main method, but changing it to a field instead of local method would fix that, then the infinite looping occurs because the server sends a packet to the same port it is listening on. There's your problem. Do you supply the same numbers as the first and second arguments to your program?
From the server, you can use receivePacket.getPort() to get the port where the packet came from.
EDIT:
Your two classes have much repetition, which is probably a source of confusion. One class has a main which starts a client then creates a server type loop tester. The other class sets up a Server then creates a client type tester.
Below is only the class you've named UDPThreadServer with comments showing changes to make the server 'work' with the testing code in the main method. Note that the server should send to a port that it is not listening to. You are also reading port values from command line arguments. I just made up some numbers for the ports and stuck them in as constants.
public class UDPThreadServer extends Thread
{
public static int port1;
UDPThreadServer()
{
//server or client? it's hard to say. you call the socket a clientSocket.
System.out.println("Starting threaded server");
start();
}
public void run()
{
try
{
// Here client(?) is set up with empty constructor.
// It is a mystery what port it will get.
DatagramSocket clientSocket = new DatagramSocket();
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(inFromUser);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (in.hasNextLine())
{
String sentence = in.nextLine();
// inFromUser.readLine();
sendData = sentence.getBytes();
// sending to port1? that must be the server.
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port1);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER: " + modSentence);
}
// clientSocket.close();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
}
// Create server
public static void main(String[] args)
{
// int port = Integer.parseInt(args[0]);
int port = 1927; // or whatever
// port1 = Integer.parseInt(args[1]);
port1 = 1928;
new UDPThreadServer();
try
{
// server resides on port1? if client sends to port 1, then this is so.
DatagramSocket serverSocket = new DatagramSocket(port1);
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());
SocketAddress address = receivePacket.getSocketAddress();
System.out.println("Received from " + address + " : " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String capSentence = sentence.toUpperCase();
sendData = capSentence.getBytes();
// where did you get the info from? Client is set up with an empty constructor, so it is a mystery.
port = receivePacket.getPort();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
// serverSocket.close();
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
Don't close the socket.
If that doesn't answer your question you need to clarify it.
while(true) is an infinite loop. Do you quit it in any case?

Categories