When client sends a message to server, the message gets truncated - java

I'm new to multithreading. Im trying to do sending of messages between a client and a server. When I send a message to the server, my output in the server is supposed to be "Aji Computer: Thanks! :D", but instead I get a truncated data "Aji Computer: Thank".
Server code
public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
in.close();
socket.receive(packet);
String dString = "Wassup " + packet.getAddress().getHostName() + "!";
//if (in == null) dString = new Date().toString();
//else dString = getNextQuote();
buf = dString.getBytes();
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
//THIS IS WHERE IM SUPPOSE TO PRINT "Aji Computer: Thanks! :D". But it prints out wrongly
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(received);
socket.close();
Client code
DatagramSocket socket = new DatagramSocket();
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName("Aji Computer");
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Server: " + received);
//THIS IS WHERE I SENT MY "Aji Computer: Thanks! :D" PACKET TO SERVER.
buf = new byte[256];
String str = "Aji Computer: Thanks! :D";
buf = str.getBytes();
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
socket.close();
}
Just to let you know, this code is from Oracle. I modified a bit so that I would know how it works.

You reassign the size of your byte array from 256 bytes to: buf = dString.getBytes(); And further down in the program you created a new packet to receive on using packet = new DatagramPacket(buf, buf.length); This uses the length of dString.getBytes() instead of byte[256] I am assuming that dString.getBytes() has less space than "Aji Computer: Thanks!"
Try reassigning your byte array to its original value:
buf = new byte[256];
EDIT: removed 'byte' from above

Related

Java Object send on Network

Details d = new Details(5425, "Vosu Mittal/CN");
ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectoutputstream = new ObjectOutputStream(byteoutputStream);
objectoutputstream.writeObject(d);
sendData = byteoutputStream.toByteArray();
DatagramPacket sendpacket = new DatagramPacket(sendData, sendData.length, internetAddress, port);
socket.send(sendpacket);
Server Side Code is
receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
System.out.print("Connected to Server");
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
int packetsize = receivePacket.getLength();
byte[] bytecount = receivePacket.getData();
ByteArrayInputStream byteinputStream = new ByteArrayInputStream(bytecount);
ObjectInputStream objectinputStream = new ObjectInputStream(byteinputStream);
Details d = (Details)objectinputStream.readObject();
String data = new String(d.toString());
System.out.println("\t"+ data+ "\tIP Address is = "+ IPAddress+ "\tPort Address is ="+ port+ "\tByte Count is = "+ packetsize );
String reply = "Thank you for the message";
My class is defined as Follows with Serializable Interface
int id;
String name;
private void showDetails(){
System.out.println("Id:"+id);
System.out.println("Name:"+name);
}
Still, I am not able to get them on the client side, rectify the code if required?

How to run Client program on fixed port in UDP connectionless client - server pair in java

I am trying to understand UDP connectionless client - server pair. I got some code in the Book Computer Networking: A Top Down Approach.
The Programs are as follows:-
UDPServer.java:
import java.io.*;
import java.net.*;
class UDPServer
{
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());
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);
}
}
}
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();
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, 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();
}
}
In the given code we have fixed the port no for the Server ,i.e., 9876.
I am curious to know that how to fix the port for Client, as we did for Server in the given java program, so that message can be returned to Client on the Specific Port.
For example, if the
client will send a UDP message to the server, the server will start and run on port number 9876 and return the original message to the client on port 9877. Please help.
You don't need a fixed port at the client, any more than the client needs a fixed IP address. Your own code should already work correctly. However there are other issues:
String sentence = new String( receivePacket.getData());
Wrong. It should be String sentence = new String( receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());.
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);
This code will send the reply back to from whence the request came. An easier way is to use the same DatagramPacket for both receive and send, and just change the data.

Sending double from matlab to java via UDP-packets

I'm trying to send doubles from Matlab(Simulink) to java.
This is my code:
public static void main(String[] args) throws SocketException, UnknownHostException, IOException {
DatagramSocket socket = new DatagramSocket(25000);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true) {
socket.receive(packet);
String msg = new String(buf, 0, packet.getLength());
Double x = ByteBuffer.wrap(buf).getDouble();
System.out.println(x);
packet.setLength(buf.length);
}
}
I'm getting values but they really don't make sense...
Most likely you are sending doubles as little-endian but ByteBuffer assumes "network order" which is big-endian.
try
DatagramSocket socket = new DatagramSocket(25000);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
DoubleBuffer db = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
while (true) {
socket.receive(packet);
db.limit(packet.getLength() / Double.BYTES);
double x = db.get(0);
System.out.println(x);
}
Note: UCP is lossy, so some packets will be lost.

Multicast a file to a group of users

I have a problem to send a file to a group of users. Users could receive the file was sent from server but the file would not be saved if it is less than 8kb.
Here is the code:
MulticastSocketServer
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MulticastSocketServer{
public static void main(String[] args) {
String fileName;
String address = "235.0.0.1";
int port = 2222;
Scanner in = new Scanner(System.in);
System.out.print("Please enter file name : ");
fileName = in.next();
try (DatagramSocket serverSocket = new DatagramSocket()) {
InetAddress addr = InetAddress.getByName(address);
BufferedReader br = new BufferedReader(new FileReader(fileName + ".txt"));
DatagramPacket fn = new DatagramPacket(fileName.getBytes(),fileName.getBytes().length, addr, port);
serverSocket.send(fn);
DatagramPacket msgPacket = null;
String txt = "";
while((txt = br.readLine())!=null){
msgPacket = new DatagramPacket(txt.getBytes(),txt.getBytes().length, addr, port);
serverSocket.send(msgPacket);
System.out.println(txt);
}
}catch (IOException ex) {ex.printStackTrace();}
}
}
MulticastSocketClient
import java.io.*;
import java.net.*;
public class MulticastSocketClient {
public static void main(String[] args) throws UnknownHostException {
int port = 2222;
String address = "235.0.0.1";
InetAddress addr = InetAddress.getByName(address);
byte[] buf = new byte[64];
byte[] buf2 = null ;
try (MulticastSocket clientSocket = new MulticastSocket(port)){
clientSocket.joinGroup(addr);
DatagramPacket fn = new DatagramPacket(buf, buf.length);
clientSocket.receive(fn);
String name = new String(buf, 0, buf.length);
String fileName = name.trim();
try(PrintWriter pw = new PrintWriter(new FileWriter(fileName+"2.txt"))){
while (true) {
buf2 = new byte [1024];
DatagramPacket msgPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(msgPacket);
String msg = new String(buf2,0,buf2.length);
String txt = msg.trim();
pw.println(txt);
System.out.println(txt);
}
}catch(FileNotFoundException ex){ex.printStackTrace();}
} catch (IOException ex) {ex.printStackTrace();}
}
}
You're never exiting the while (true) loop, because you don't have any mechanism for transmitting end of stream, so you're never closing the PrintWriter, so it isn't flushing its final buffer, so any file < 4096 chars won't get flushed at all, so it will be zero length.
However your code has much worse problems that this. You are assuming:
the filename fits into 1024 characters
every line of the input file fits into 1024 bytes
the filename is received first
all the content packets are received
all the content packets are received in order
all the content packets are received exactly once
the length of every datagram is 1024
the data is text, not binary, and can be converted losslessly to a String
You're using UDP. That means that most of these assumptions are invalid.

error in transferring file using tcp in java

I am developing a web app using jsp in which i use a tcp connection to send a file from server to a client. But while doing so, the program goes into an infinite loop.
It doesn't return anything. Can anyone please help me?
I am posting the server and client code here.
Server code:
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = "FILE".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5006);
clientSocket.send(sendPacket);
sendData = file.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5006);
clientSocket.send(sendPacket);
ServerSocket serverSocket = new ServerSocket(5494);
Socket socket = serverSocket.accept();
File transferFile = new File("C:\\Users\\Krishna\\Documents\\LanMan\\" + file);
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray, 0, bytearray.length);
OutputStream os = socket.getOutputStream();
os.write(bytearray, 0, bytearray.length);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String a = (new String(receiveData, "UTF-8")).trim();
//if(a.equals())
os.flush();
//bin.close();
socket.close();
serverSocket.close();
Client code:
if (a.startsWith("FILE")) {
byte b[] = new byte[1024];
received = new DatagramPacket(receiveData, receiveData.length);
serversocket.receive(received);
a = (new String(receiveData, "UTF-8")).trim();
int filesize = 2022386;
int bytesRead;
int currentTot = 0;
socket = new Socket(ip, 5494);
byte[] bytearray = new byte[filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\LanMan\\" + a);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray, 0, bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length - currentTot));
if (bytesRead >= 0) currentTot += bytesRead;
} while (bytesRead > -1);
bos.write(bytearray, 0, currentTot);
bos.flush();
bos.close();
//fos.close();
//is.close();
sendData = "OK".getBytes();
DatagramPacket send = new DatagramPacket(sendData, sendData.length, ip, port);
serversocket.send(send);
socket.close();
}
You implemented a deadlock.
The server writes the file content, then wait for a datagram packet from the client, the closes the socket.
The client reads until the server closes the socket, then sends a datagram packet.
So each party is waiting for the other one.
Also, never ignore the result of the InputStream.read() method like you're doing in the server code. You can never assume that all the file will be read in one single call.

Categories

Resources