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?
Related
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.
For some reason, the data in my datagramsocket wont send. Im trying to make a simple chatclient.
Here is how my chat client is going to work:
The person enters the username
They enter the IP
It connects
They send messages
Here is my code:
Client 1 (Sends and recieves):
// Server Info
public static int serverPort = 8743;
public static String serverName = "ServerName";
// Functions for the server
#SuppressWarnings("resource")
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
System.out.println("You are now the host.");
boolean enteredDetails = false;
String username = null;
String ipAddress = null;
System.out.print("Enter your username: ");
Scanner userInput = new Scanner(System.in);
if (userInput.hasNext()) {
username = userInput.next();
}
System.out.print("Enter the IP: ");
if (userInput.hasNext()) {
ipAddress = userInput.next();
enteredDetails = true;
}
while (true) {
Scanner message = new Scanner(System.in);
if (message.hasNextLine()) {
String messageFormat = username + ": " + message.nextLine();
byte[] sendData = messageFormat.getBytes();
InetAddress IPAddress = InetAddress.getByName(ipAddress);
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, InetAddress.getByName(ipAddress), 9876);
serverSocket.send(sendPacket);
System.out.println(messageFormat);
}
// Recieve text
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println(sentence);
}
}
For the second client (recieves only):
#SuppressWarnings("resource")
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
boolean enteredDetails = false;
String username = null;
String ipAddress = null;
System.out.print("Enter your username: ");
Scanner userInput = new Scanner(System.in);
if (userInput.hasNext()) {
username = userInput.next();
}
System.out.print("Enter the IP: ");
if (userInput.hasNext()) {
ipAddress = userInput.next();
enteredDetails = true;
}
while (true) {
// Recieve text
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println(sentence);
}
}
Client 1:
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, InetAddress.getByName(ipAddress), 9876);
This client is sending to port 9876.
Client 2:
DatagramSocket serverSocket = new DatagramSocket();
There's no way this client is ever going to receive anything, as it is receiving on an unknown port which is different every time you run it. It should be:
DatagramSocket serverSocket = new DatagramSocket(9876);
I have written the following two codes for finding GCD of two numbers. (via UDP Server)
GCD_UDPClient.java
import java.io.*;
import java.net.*;
class GCD_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];
System.out.print("First Number: ");
String input1 = InFromUser.readLine();
System.out.print("Second Number: ");
String input2 = InFromUser.readLine();
String Input = input1 + ' ' +input2;
SendData = Input.getBytes();
DatagramPacket SendPacket = new DatagramPacket(SendData, SendData.length, IPAddress, 9836);
ClientSocket.send(SendPacket);
DatagramPacket ReceivePacket = new DatagramPacket(ReceiveData, ReceiveData.length);
ClientSocket.receive(ReceivePacket);
String ModifiedInput = new String(ReceivePacket.getData());
System.out.println("GCD From Server: " +ModifiedInput);
ClientSocket.close();
}
}
GCD_UDPServer.java
import java.io.*;
import java.net.*;
#SuppressWarnings("unused")
class GCD_UDPServer
{
#SuppressWarnings("resource")
public static void main(String args[]) throws Exception
{
DatagramSocket ServerSocket = new DatagramSocket(9836);
byte[] ReceiveData = new byte[1024];
byte[] SendData = new byte[1024];
while(true)
{
DatagramPacket ReceivePacket = new DatagramPacket(ReceiveData, ReceiveData.length);
ServerSocket.receive(ReceivePacket);
String input = new String(ReceivePacket.getData());
InetAddress IPAddress = ReceivePacket.getAddress();
int port = ReceivePacket.getPort();
int ar[] = new int[2],i=0;
for (String Number: input.split(" ", 2))
{
ar[i] = Integer.parseInt(Number);
i=i+1;
}
String Answer = Integer.toString(calculategcd(ar[0],ar[1]));
SendData = Answer.getBytes();
DatagramPacket SendPacket = new DatagramPacket(SendData, SendData.length, IPAddress, port);
ServerSocket.send(SendPacket);
}
}
public static int calculategcd(int a, int b)
{
if(b%a == 0)
return a;
else
return calculategcd(b%a,a);
}
}
ClientSocket.receive(ReceivePacket); doesn't seem to work properly, any clues why? Full codes are posted only for clarity.
Output given by the above codes:
First Number: 5
Second Number: 25
[waits indefinitely]
Output Required:
First Number: 5
Second Number: 25
GCD From Server: 5
You are sending 1024 bytes to the server, and you placed your data in a String like "5 25". When you receive the data you split it and you will have "5", and "25" followed by the other bytes in your buffer. Either you use Number.trim() to throw away those extra bytes, or you send a smaller packet (if that is possible).
I had a test , the GCD_UDPServer.java have a exception like
Exception in thread "main" java.lang.NumberFormatException: For input string: "12"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at GCD_UDPServer.main(GCD_UDPServer.java:24)
and simply change line 24
ar[i] = Integer.parseInt(Number);
to
ar[i] = Integer.parseInt(Number.trim());
and it works properly.
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.
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