Receiving Datagram packets are not displayed - java

I was trying to make a small java program which writes a text message from server to client using DatagramServer and DatagramPacket.
This is the code i've written on the server and client portion.
serverm.java
byte b[] = new byte[1200];
System.out.println("Enter some text");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputMessage = br.readLine();
b = inputMessage.getBytes();
DatagramSocket d = new DatagramSocket(6125);
DatagramPacket p = new DatagramPacket(b,i,InetAddress.getLocalHost(),5461);
d.send(p);
clientm.java
byte b[] = new byte[1024];
try
{
DatagramSocket d = new DatagramSocket(5461);
DatagramPacket p = new DatagramPacket(b,1024);
d.receive(p);
String outputMessage = new String(p.getData(),0,p.getLength());
System.out.println(outputMessage);
}
When running the java program, it runs when the server sends a message to the client - the received message only prints empty line. How can i get the string to be displayed ?

I was able to reproduce your problem when I set the 'i' variable in your server to 0.
Make sure that value is the length of the packet you're sending.

Related

Stream Compression - what am I doing wrong?

For one of my projects, I'm wanting to compress a data stream and transmit over a socket. What I've done so far is
echoSocket = new Socket(SERVER_HOST_NAME, PORT);
consoleIn = System.in;
clientIn = echoSocket.getInputStream();
clientInputUnzipper = new InflaterInputStream(clientIn);
clientOut = echoSocket.getOutputStream();
clientOutputZipper = new DeflaterOutputStream(clientOut);
int r = 0, rc = 0;
System.out.println("Connection achieved to HostName : " + SERVER_HOST_NAME + " on port " + PORT);
while((r = consoleIn.read()) != END_OF_STREAM)
clientOutputZipper.write(r)
On my client side. And it seems to be sending the first byte fine (I troubleshooted the client side to confirm this). But my reader on my server side seems to be unable to read.
serverInputStream = clientSocket.getInputStream();
serverInputUnzipper = new InflaterInputStream(serverInputStream);
serverOutputStream = clientSocket.getOutputStream();
serverOutputZipper = new DeflaterOutputStream(serverOutputStream); //used to send the data back to the client
fileOutput = new FileOutputStream(log);
fileFilterOutput = new FilterOutputStream(fileOutput);
int r = 0, c = 0;
while((r = serverInputUnzipper.read()) != END_OF_STREAM) //getting stuck on this line (waiting for input)
Given that I've sent through the first byte, shouldn't the serverInputStream receive it? However, given it's stalled, I'd assume that it's waiting to read some data (the serverInputUnzipper.read() function). Why didn't it receive the data byte as intended?
Thanks in advance (I've spent a good portion of today trying to fix this presumably simple bug)

Transferring Large Data with UDP protocol

I know TCP is better to send file but I have a homework about sending file via udp protocol . Is there any code example in C# or Java about sending file?
I have server-client example to send and recieve message. I tried to send the file using the same way but could not succeed. I may need an algorithm to divide the file small parts and send them via datagram, and I have an idea to put "md5" of the part as header of the array to check if the packet is lost or not.
Here is my try , my server side in java;
// 1. creating a server socket, parameter is local port number
sock = new DatagramSocket(7777);
// buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
byte []bigByteArray=new byte[1024*1024*1024*1024];
// 2. Wait for an incoming data
echo("Server socket created. Waiting for incoming data...");
ByteBuffer target = ByteBuffer.wrap(bigByteArray);
// communication loop
while(true)
{
try
{
sock.receive(incoming);
String s = new String(incoming.getData());
if(s=="finish") break;
target.put(incoming.getData());
}
catch(Exception e)
{
}
}
fos.write(bigByteArray);
fos.close();echo("RECIEVED");
and my client side;
String s;
Path path=Paths.get("C:\\Users\\Toshiba\\Desktop\\aa.txt");
byte[] data = Files.readAllBytes(path);
try
{
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost");
//take input and send the packet
byte [] part;
for (int i = -1; i < data.length; i=i+100)
{
if(sock.isConnected())
{
part=Arrays.copyOfRange(data,i+1,i+100 );
}
else i=i-100;
}
byte [] f="finish".getBytes();
DatagramPacket finalpac = new DatagramPacket(f ,f.length , host , port);
sock.send(finalpac);
}
Thank you in advance.
Several issues:
The following isn't correct:
sock.receive(incoming);
String s = new String(incoming.getData());
The final line should be
String s = new String(incoming.getData(), incoming.getOffset(), incoming.getLength());
and if you aren't receiving text you shouldn't be converting the data to a String at all.
Remove the sock.isConnected() test. DatagramSockets are not usually connected, and you certainly haven't connected this one.
The loop in which this is embedded does nothing useful. You are only sending the word "finish".

Why am i getting weird character in socket inputstream

// Portion of code copied from the senders side
clientSocket = new Socket(successor.IP, successor.PORT);
toServer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String message = "deleteme\n"+predecessor.IP+","+predecessor.PORT;
toServer.write(message);
toServer.newLine();
toServer.flush();
// Portion of code copied from the receivers side
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
input = fromClient.readLine();
On the receivers side there are weird characters before the deleteme. Like the clubs ♣.
I want to know from where do these characters come and how to fix the problem? The temporary fix that I am doing is that before I send the deleteme message I send some garbage data like abcd. Then the deleteme get there as it is.

Problems with UDP Received and Sent UDP Packages?

I am trying to write a simple program about UDP Connections to learn about them. I have implemented some basic things but when I try to send and get back what I sent but I face some problems like,
When I do this ;
send a string
"asd" to server I get back asdxxxxxxxxxx
and when I try to print What I get in the server I get [B#5f186fab
How can I solve this problem ?
To be more clear I am sending you a few lines of code ,
In client;
Scanner in = new Scanner(System.in);
String result = in.nextLine();
// send request
byte[] buf = new byte[1000];
String read = result;
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(result.getBytes(), result.getBytes().length, address, 4445);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Quote of the Moment: " + received);
In server ;
byte[] buf = new byte[1000];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
byte[] received = packet.getData();
System.out.println(received.toString());
// figure out response
// send the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(received, received.length, address, port);
socket.send(packet);
Thank you all
EDIT 1 I think I have problems with my buffer but I dont know how to solve .
You can use
System.out.println(Arrays.toString(received));
but what you probably want is
System.out.println(new String(received, o, lengthRead, "UTF-8"));
Have you fixed this?
Otherwise, what I've found is that if you declare a receiving byte[] buf with a capacity that's greater than the length string you're actually receiving, you'll end up with the rest of the buffer full of unwanted bytes.
Eg. if you declare byte[] received = new byte[1000]; but only receive a string of 4 bytes, you'll end up with 996 unwanted bytes.
One quick way around this is to do something like
byte[] received = packet.getData();
System.out.println(received.toString().trim());
trim() did the trick for me. Hope that helps you!

Use datagrams in java to send video/audio from client to server?

Hey everyone, I'm having a bit of a problem with UDP and Datagrams. I'm supposed to make a server that will get a request from the client to send a file in the same directory. The UDP Server will then get this file (a video), put it into a datagram and send it. I think I know how to do it, but I can't put the file in the datagram. I'm putting it in Binary form, so keep that in mind.
Here's my code so far:
edit: This is the server by the way, and I keep having trouble with BufferedInputReader and OutputReader, so keep that in mind :)
Scanner inFromUser = new Scanner(System.in);
int port = 12345;
DatagramSocket server = new DatagramSocket(port);
// Read name of file supplied by client (must be a line of text):
Scanner in = new Scanner(new DataInputStream(server.getInputStream()));
String filename = in.nextLine();
DatagramSocket request = server.accept();
// Create buffer, then we're ready to go:
// Puts file into binary form
BufferedInputStream inbinary =
new BufferedInputStream(new FileInputStream("poop.txt"));
// Outputs the binary form
BufferedOutputStream outbinary =
new BufferedOutputStream(request.getOutputStream());
int numbytes;
int countblocks = 0;
int countbytes = 0;
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length, port);
server.receive(packet);
while ((numbytes = inbinary.read(buf,0,1024)) >= 0)
{
// receive packet from client, telling it to send the video file
server.receive(packet);
InetAddress address = packet.getAddress();
packet = new DatagramPacket(buf, buf.length, address, port);
server.send(packet);
countblocks++; // keep statistics on file size
countbytes += numbytes;
outbinary.write(buf,0,numbytes); // write buffer to socket
}
outbinary.flush(); // FLUSH THE BUFFER
server.close(); // done with the socket
System.out.println(countblocks + " were read; " + countbytes + " bytes");
}
}
I haven't done datagrams in a while, but I'm pretty sure the accept() call is wrong. That's for TCP servers.
I'd recommend cribbing from Sun's excellent tutorial: http://java.sun.com/docs/books/tutorial/networking/datagrams/clientServer.html

Categories

Resources