i have written a simple UDP server program which receives data packets from a network controller(Aruba) but prints the output junk characters as below. Tried setting character Set to UTF-8 but didnt help.
public class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9999);
byte[] receiveData = new byte[2048];
byte[] sendData = new byte[2048];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0,
receivePacket.getLength(), "UTF-8");
System.out.println("RECEIVED: " + response);
}
}
}
output :
RECEIVED: ��drÈ�Z��ï¿]о�,E!ï¿Uo�¿½ï¿½f�`�
RECEIVED: �(drÈ$w�D ��k�O���?�NQ��
pECEIVED: ��dr��.O�dLI�,O����u�
VT102RECEIVED: �Ddr��a�cd���k0��-���I�Q
RECEIVED: �dr���V���;;k��
$o���
ECEIVED: �^
Related
I cant figure out how to attach a sequence number to a datagram packet over a UDP connection. See code below:
public class Client {
public static void main(String args[]) throws Exception
{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
Integer SN = 1;
// create byte arrays for sending and receiving data
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
// file reader
FileReader fr = new FileReader("umbrella.txt");
BufferedReader br = new BufferedReader(fr);
String fileText;
fileText = br.readLine();
System.out.println(fileText);
// convert to bytes
byte [] fileBytes = fileText.getBytes();
//byte [] seqNumBytes = ByteBuffer.allocate(4).putInt(SN).array();
//concatenate sequence number with file:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
DataOutputStream dos = new DataOutputStream(outputStream);
dos.write( fileBytes );
dos.writeInt(SN);
byte [] concatData = outputStream.toByteArray( );
sendData = concatData;
// send packet
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 102);
clientSocket.send(sendPacket);
As can be seen ive tried to concatenate the sequence number (SN) which is set to 1.
When I run the server and client my server picks up the text file and simply returns the contents without the sequence number.
see particularly this snip:
//concatenate sequence number with file:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
DataOutputStream dos = new DataOutputStream(outputStream);
dos.write( fileBytes );
dos.writeInt(SN);
byte [] concatData = outputStream.toByteArray( );
sendData = concatData;
How do I attach a sequence number to each datagram packet and have that read on the server side?
I try to read the UDP Stream from X-Plane 12 in Java.
This is what I try:
public class EchoClient {
#Test
public void echo() throws IOException {
DatagramSocket socket;
InetAddress address;
byte[] buf;
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
String msg = "TEST";
buf = msg.getBytes();
DatagramPacket packet
= new DatagramPacket(buf, buf.length, address, 49000);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
System.out.println("hi there");
while(true) {
socket.receive(packet); // it "stops" here... without an error
String received = new String(
packet.getData(), 0, packet.getLength());
System.out.println(received);
}
}}
X-Plane is running and the UDP option is activated - but my program does print nothing on the console.. and it is runnig forever (while true)
Receive is blocked and waiting to a receive a packet. The packet you sent earlier is dropped on the floor because no one is listening.
I'm devolping an SMS application that uses UDP protocol . My application need to do the following , client send to another client a message doesn't exceed 160 and he/she know the other client IP address . It will send through a server which will save it in case client is offline .
I started working on it but then I stopped ! I was having problem with these things .
How can multiple clients sends to server ? I searched about and I read about something called mutithreading , can anyone explain or give me example for it ?
also , I couldn't imagin the process of taking messages from clients and then saving it . I mean how the server know which message belong to which client ?
this is the code which I'm working on it
server :
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
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());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String senderSentence = "From "+IPAddress+" Msg "+sentence;
sendData = senderSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
} } }
client :
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws Exception
{
String sentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
do {
System.out.println("Enter a msg , NOTE: don't exceed 160 charcter");
sentence = inFromUser.readLine();
}
while(sentence.length() >= 160);
System.out.println("Enter the adress of the other user");
String ip=inFromUser.readLine();
InetAddress IPAddress = InetAddress.getByName(ip);
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());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
} }
Thank you ~
I'm not sure why you need to use UDP - but if this isn't some special requirement you might want to look at using a web server.
I quite like the Play Framework for Java, which is going to handle the threading for you. Every time you send a message to the server it is just like sending a request for a web page, so you can reply with JSON or XML or whatever you think is best.
This is going to be a lot easier than handling all the socket communication yourself - but as I say, maybe you have a special requirement.
Hope this helps!
As stated in my title, I'm trying to build a very simple file transfer service in java. Right now, all I have been able to do in construct a simple client/server that can send and receive strings of text. Here is the code:
UDPClient.java:
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader
(System.in));
DatagramSocket clientSocket = new DatagramSocket();//port # is assigned by OS to the client
InetAddress IPAddress =
InetAddress.getByName("localhost");
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
byte[] sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length,
IPAddress, 7777); //data with server's IP and server's port #
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
clientSocket.setSoTimeout(1000);
clientSocket.receive(receivePacket);
// we still need to catch the exception and retry
String modifiedSentence =
new String(receivePacket.getData(),
0,
receivePacket.getLength());
System.out.println("FROM SERVER:" +
modifiedSentence);
clientSocket.close();
}
}
UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new
DatagramSocket(7777); //server will run on port #9876
byte[] receiveData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(
receivePacket.getData(),
0,
receivePacket.getLength());
InetAddress IPAddress =
receivePacket.getAddress(); //get client's IP
int port = receivePacket.getPort(); //get client's port #
System.out.println("client's port # =" + port);
System.out.println("client'sIP =" +IPAddress);
System.out.println("client's message =" +sentence);
String capitalizedSentence =
sentence.toUpperCase();
byte[] sendData = capitalizedSentence.
getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData,
sendData.length,
IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Ultimately what I'd like to do is send a file path to the server, have the server return the file, and then save it to a predetermined location like C:\Desktop\Folder.
I'm really at a loss for how to advance past where I am, so any advice, pointers, or resources that you could share would be great. I'm very new at this and feeling way out of my depth.
Thanks!
Unlike TCP UDP uses a non-persistent connection. Therefore, you will have to maintain state in the request and response packets.
For example, the request packet could look as follows.
2 bytes - File name length
(variable) - File name 4 bytes - Start position
4 bytes - Seq. no.
4 bytes - Max chunk size
Server will read upto 'Max chunk size' bytes from 'Start position' and return to client in following format. The Seq. no. will be echoed back from request so client can relate request with response.
1 byte - Response code
4 byte - Seq. no.
4 bytes - Payload length
(variable) - Payload
This is kind of a followup to the question I had yesterday. I had a homework assignment to send and receive data with a client/server TCP socket connection. I would like to make a version of it using UDP. The idea is that I can redirect standard I/O and send the streams using UDP. For example, if I type in:
server: java UDPServer 5555 < file1.txt
client: java UDPClient localhost 5555 > file2.txt
It should send the data in file1.txt from the server to client's file2.txt. When I run the client/server pair in separate terminals, file2.txt is created but the data is never actually sent. Instead it seems like I am stuck in an infinite loop, where I cannot enter anything into the terminal unless I kill the application.
The server code is:
public static final int BUF_SIZE = 256;
public static void main(String[] args) throws IOException{
port = Integer.parseInt(args[0]);
DatagramSocket serverSocket = new DatagramSocket(port);
BufferedInputStream input = new BufferedInputStream(System.in);
BufferedOutputStream output = new BufferedOutputStream(System.out);
byte[] receiveData = new byte[BUF_SIZE];
byte[] sendData = new byte[BUF_SIZE];
byte[] buf = new byte[BUF_SIZE];
String sentence;
if(System.in.available() > 0) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
InetAddress address = receivePacket.getAddress();
int bytesRead = 0;
while((bytesRead = input.read(buf, 0, BUF_SIZE)) != -1) {
sentence = new String(buf, 0, bytesRead);
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
serverSocket.send(sendPacket);
}
} else {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
sentence = new String(receivePacket.getData());
output.write(sentence.getBytes());
}
serverSocket.close();
input.close();
output.close();
}
And the client code is:
public static final int BUF_SIZE = 256;
public static void main(String[] args) throws IOException{
String hostName = args[0];
port = Integer.parseInt(args[1]);
DatagramSocket clientSocket = new DatagramSocket();
InetAddress address = InetAddress.getByName(hostName);
BufferedInputStream input = new BufferedInputStream(System.in);
BufferedOutputStream output = new BufferedOutputStream(System.out);
byte[] sendData = new byte[BUF_SIZE];
byte[] receiveData = new byte[BUF_SIZE];
byte[] buf = new byte[BUF_SIZE];
String sentence;
if(System.in.available() > 0) {
int bytesRead = 0;
while((bytesRead = input.read(buf, 0, BUF_SIZE)) != -1) {
sentence = new String(buf, 0, bytesRead);
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
clientSocket.send(sendPacket);
}
} else {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
sentence = new String(receivePacket.getData());
output.write(sentence.getBytes());
}
clientSocket.close();
input.close();
output.close();
}
I am still new to socket programming so I am basing this off of example code in my textbook. Is there some glaring mistake that I am making that is preventing the data from being transferred? Thanks very much for your patience and help!
The first problem you have is that client.main doesn't run because your shell command is wrong. For some reason, with Java you can't redirect output how it's traditionally done. You can simply put a few print statements at the beginning of client.main to see nothing executes. Try this:
java UDPClient localhost 5555 | tee file2.txt
See redirect Java output.
The other problem you have is that both the client and server are waiting to receive a datagram. You have in the server code:
if(System.in.available() > 0) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
And you have in the client code:
else {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
sentence = new String(receivePacket.getData());
output.write(sentence.getBytes());
}
Note that the else statement will always execute because System.in.available will always return 0. Remember your not redirecting input to the client, so there's nothing in System.in. To fix this you need to first send a client datagram so that the server can respond with the contents of file2.txt.
You're missing all the things you need to do to make this work. Where's the code to do transmit pacing, retransmissions, acknowledgements, reordering, and so on? If you want to use UDP, you have to do yourself all the things TCP does for you.
See, for example RFC 1350 for an example of a file transfer protocol layered on top of UDP.