sending file using UDP multicast - java

I have a problem where I want to send my file to my friend using UDP multicast, but when I try to run the code the output is this:
Output:
Exception in thread "main" java.lang.IllegalArgumentException: illegal length or offset
at java.net.DatagramPacket.setData(Unknown Source)
at java.net.DatagramPacket.<init>(Unknown Source)
at Source.createConnection(Source.java:44)
at Source.main(Source.java:102)
And this is my code:
import java.io.*;
import java.net.*;
public class Source {
private DatagramSocket socket = null;
private FE event = null;
private String sourceFilePath = "C:/joe's/file/text/hai.txt";
private String destinationPath = "C:/maria/file2/laboratory/";
private String hostname= "192.168.43.65";
public Source(){ }
public static void main1(String[] args)throws Exception
{
try
{
DatagramSocket s = new DatagramSocket();
byte[]line = new byte[100];
System.out.print("Enter text to send");
int len = System.in.read(line);
InetAddress dest = InetAddress.getByName("192.168.43.65");
DatagramPacket pkt = new DatagramPacket(line,len,dest,16900);
s.send(pkt);
s.close();
}
catch(Exception err){
System.err.println(err);
}
}
public void createConnection() {
try {
socket = new DatagramSocket();
byte[] incomingData = new byte[9999];
event = getFE();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(event);
byte[] data = outputStream.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, 9876);
socket.send(sendPacket);
System.out.println("File sent from AppsA");
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
incomingData.length);
socket.receive(incomingPacket);
String response = new String(incomingPacket.getData());
System.out.println("Response from AppsB:" + response);
Thread.sleep(2000);
System.exit(0);
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public FE getFE() {
FE fileEvent = new FE();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1,
sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile())
{
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
}
else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
return fileEvent;
}
public static void main(String[] args)throws Exception {
Source app = new Source();
app.createConnection();
}
}

Your problem lies in improper use of DatagramPacket constructors:
DatagramPacket sendPacket = new DatagramPacket(data, data.length, 9876);
The above line is correct however, the code below:
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
incomingData.length);
Should be this:
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
9876);
The second argument in the DatagramPacket constructor is the length. You initially set the length on sendPacket to 9876

Related

Request a file and transfer file using java socket

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Socket socket = new Socket(jTextField1.getText(), 15123);
OutputStream oStream = new BufferedOutputStream(socket.getOutputStream());
String name = jTextField2.getText();
DataOutputStream d = new DataOutputStream(oStream);
d.writeUTF(name);
oStream.flush();
oStream.close();
}catch(IOException e){
}
}
public static void main(String args[]) throws IOException {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new testGUI().setVisible(true);
try {
ServerSocket serverSocket3 = new ServerSocket(15123);
Socket socket3 = serverSocket3.accept();
InputStream iStream3 = socket3.getInputStream();
DataInputStream d3 = new DataInputStream(iStream3);
InetAddress ip = socket3.getInetAddress();
String t = d3.readUTF();
Socket socket1 = new Socket(ip.toString(), 3333);
OutputStream oStream1 = new BufferedOutputStream(socket1.getOutputStream());
File folder = new File("C:");
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++){
String filename = listOfFiles[i].getName();
String fi = d3.toString();
String[] fn = fi.split("\\.");
if(filename.startsWith(fn[0]) && listOfFiles[i].getName().endsWith(fn[1])){
DataOutputStream d1 = new DataOutputStream(oStream1);
d1.writeUTF(d3.toString());
File file1 = new File(folder.toString()+"/"+filename);
InputStream iStream1 = new FileInputStream(file1);
byte[] buffer = new byte[(int) file1.length()];
for (int readCount = iStream1.read(buffer); readCount != -1; readCount = iStream1.read(buffer)) {
oStream1.write(buffer, 0, readCount);
}
oStream1.flush();
oStream1.close();
iStream1.close();
}
}
} catch (IOException e) {
}
}
});
try {
ServerSocket serverSocket1 = new ServerSocket(3333);
Socket socket1 = serverSocket1.accept();
InetAddress ip = socket1.getInetAddress();
InputStream iStream1 = socket1.getInputStream();
DataInputStream d = new DataInputStream(iStream1);
FileOutputStream oStream1 = new FileOutputStream(d.readUTF());
byte[] buffer = new byte[8192];
int count;
while ((count = iStream1.read(buffer)) > 0) {
oStream1.write(buffer, 0, count);
}
oStream1.flush();
oStream1.getFD().sync();
oStream1.close();
iStream1.close();
JOptionPane.showMessageDialog(null, "File recived"+ip.toString(), "Notification", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
}
}
problems- (netbean code)
1)Not load GUI
2)not sending request file to another pc.
my task is; If some one request a file from someone, it search form shared location(per defined) and get the file and send it back to the requester.
need a help

Java: Send and receive byte array

Well, I want to write a simple java client-server-programme, which exchanges byte arrays over tcp-sockets.
/* Server */
public class Server {
private ServerSocket Server = null;
private Socket Client = null;
public static void main(String[] args) {
Server A = new Server();
A.runServer();
A.listenServer();
}
public void runServer() {
try {
Server = new ServerSocket(1234);
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
System.exit(-1);
}
}
public void listenServer() {
try {
while (true) {
System.out.println("Waiting...");
Client = Server.accept();
System.out.println("Got something new");
readMessage(Client);
}
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
}
public byte [] readMessage (Socket socket) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1];
int len = -1;
while((len = socket.getInputStream().read(buf))!=-1){
baos.write(buf, 0, len);
}
for (int i=0; i<baos.toByteArray().length; i++) {
System.out.println(baos.toByteArray()[i]);
}
return baos.toByteArray();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
return null;
}
public void writeMessage (Socket socket, String Message) {
try {
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printWriter.print(Message);
printWriter.flush();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
}
}
/* Client */
public class Client {
public static void main(String[] args) {
Client B = new Client();
B.runClient();
}
public void runClient () {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 1234);
}
catch (Exception e) {
System.out.println("Client fault: "+e.getMessage());
}
byte [] Tmp = new byte[10];
for (int i=0; i<Tmp.length; i++) {
Tmp[i] = 1;
}
writeMessage(socket, Tmp);
for (int i=0; i<10; i++) {
byte [] Message = readMessage(socket);
System.out.println(Message);
}
}
public void writeMessage (Socket socket, byte [] myByteMessage) {
try {
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.write(myByteMessage, 0, myByteMessage.length);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printWriter.print(myByteMessage);
printWriter.flush();
}
catch (Exception e) {
System.out.println("Could not send data over TCP");
return;
}
}
public byte [] readMessage (Socket socket) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1];
int len = -1;
while((len = socket.getInputStream().read(buf))!=-1){
baos.write(buf, 0, len);
}
for (int i=0; i<baos.toByteArray().length; i++) {
System.out.println(baos.toByteArray()[i]);
}
System.out.println("Test");
return baos.toByteArray();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
return null;
}
}
The problem is, that the client send something to the server but the server doesn't receive anything, so he hangs at the readMessage function.
On the other hand, the client receive some weird stuff, but not the response from the server.
The server receives bytes, but it never leaves the while loop because read() never returns -1. read() returns -1 when the end of the stream is reached. And that happens only when the client closes the socket output stream. Since the client never closes the output stream, the server keeps waiting for the more bytes to come.
Side note: your code is hard to read because you don't respect the standard Java naming conventions: variables start with a lowercase letter.

Jar file gets corrupted when sent over socket

I'm trying to send a jar file over a socket to a server.
Now everything seems to be working fine but on the other side of the socket, the jar is corrupted. The files have on both sides of the socket the same length. But when I try to use the file in bukkit, the file is corrupted.
The client code:
public class Main {
private Socket connection;
private ObjectOutputStream outStream;
private static String serverAddress = ""; // the ip address
static File fileLoc = new File("C:\\Users\\Tom\\Documents\\Qubeproject\\server\\plugins");
static String fileName = "\\WorldEdit.jar";
static File file ;
static InputStream IS;
static OutputStream OS;
static byte[] msgByte = new byte[1024];
public static void main(String[] arg0){
p("Starting this shit up");
file = new File(fileLoc + fileName) ;
try {
Socket connection = connection();
IS = connection.getInputStream();
OS = connection.getOutputStream();
OS.write(msg("LOL"));
//Authenciation
IS.read(msgByte);
if(new String(msgByte).trim().equals("OK")){
p("OK");
OS.write(msg(fileName));
//sending fileName
IS.read(msgByte);
p(new String(msgByte).trim());
//confirmation
OS.write(msg("l:" + (file.length())));
byte[] fileByte = new byte[(int)(file.length())];
FileInputStream jis = new FileInputStream(file);
int count = 0;
while((count = jis.read(fileByte))>0){
OS.write(fileByte,0,count);
OS.flush();
}
OS.flush();
setByteZero(msgByte);
IS.read(msgByte);
p(new String(msgByte).trim());
//confirmation
}else{
p("Authenciation failed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void p (String s){
System.out.println(s);
}
private static byte[] msg(String s){
return s.getBytes();
}
private static Socket connection() throws IOException{
Socket socket = new Socket();
InetAddress ip = InetAddress.getByName(serverAddress);
InetSocketAddress address = new InetSocketAddress(ip,6969);
socket.connect(address,6969);
return socket;
}
private static byte[] setByteZero(byte[] workByte) {
for(int i=0;i < workByte.length;i++){
workByte[i] = 0;
}
return workByte;
}
the server code in bukkit
public class Checkup implements Runnable{
Server serverB;
ServerSocket server;
Socket client;
InputStream IS;
OutputStream OS;
static File destination;
byte[] msgByte = new byte[1024];
String filename;
long length;
Checkup (Server serverm){
serverB = serverm;
}
#Override
public void run() {
try{
server = new ServerSocket(6969);
}catch(Exception e){
}
try{
while(true){
client = server.accept();
IS = client.getInputStream();
OS = client.getOutputStream();
IS.read(msgByte);
if(msg(msgByte).equals("LOL")){
OS.write(msg("OK"));
IS.read(msgByte);
filename = msg(msgByte);
OS.write(msg("Q received name :" + filename));
OS.flush();
setByteZero(msgByte);
IS.read(msgByte);
length = Integer.parseInt(new String(msgByte).trim().replace("l:", ""));
OS.write(msg("Q received length :" + length));
byte[] fileByte = new byte[(int)length];
destination = new File("C:\\Users\\Quentin\\Desktop\\DE server\\plugins" + filename);
FileOutputStream fos = new FileOutputStream(destination);
int count = 0;
while((count =IS.read(fileByte))>0 ){
fos.write(fileByte);
fos.flush();
}
fos.flush();
fos.close();
OS.write(msg("Q received the jar!Bye"));
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
try {
serverB.reload();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
finally{
}}
private String msg(byte[] strByte){
return new String(strByte).trim();
}
private static byte[] msg(String s){
return s.getBytes();
}
private static byte[] setByteZero(byte[] workByte) {
for(int i=0;i < workByte.length;i++){
workByte[i] = 0;
}
return workByte;
}
#Jon pointed you to the problem, here it is spelled out and formatted.....
The following code half-ignores the count (and the count is legal to be 0 too):
while((count =IS.read(fileByte))>0 ){
fos.write(fileByte);
fos.flush();
}
fos.flush();
fos.close();
and should be written as:
while((count =IS.read(fileByte))>=0 ){
fos.write(fileByte, 0, count);
}
fos.flush();
fos.close();

which stream should I use to transfer a custom file -like jpeg or mp3- over the network in java?

I've tried to write a server and a client in java, to transfer a file. but the received file is weird and look like it's filled with strange bytes and it won't open with any application, however its size is exactly same as the source file.
I don't know where the problem is! is it about encoding?
Server-side:
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) {
char sp = File.separatorChar;
String home = System.getProperty("user.home");
try {
ServerSocket server = new ServerSocket(5776);
while (true){
Socket connection = server.accept();
try {
String FileName=home+sp+"33.jpg";
File inputFile = new File(FileName);
FileInputStream Fin = new FileInputStream(inputFile);
long fileLength = inputFile.length();
byte[] bt= new byte[(int) fileLength];
DataOutputStream Oout = new DataOutputStream(connection.getOutputStream());
Oout.writeLong(fileLength);
Oout.write(bt);
Oout.flush();
Oout.close();
connection.close();
} catch (IOException ex) {}
finally {
try {
if(connection!= null) connection.close();
} catch (IOException e) {}
}
}
} catch (IOException e) {
System.err.println("There is a server on port 5776");
}
}
}
Client-side:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
byte[] IP={(byte)192,(byte)168,1,7};
char sp = File.separatorChar;
String home = System.getProperty("user.home");
String SharingPathString = home+sp+"File Sharing";
String FileName = SharingPathString+sp+"file.jpg";
try {
InetAddress add = InetAddress.getByAddress(IP);
Socket theSocket= new Socket("Shayan-8",5776);
DataInputStream in= new DataInputStream(theSocket.getInputStream());
final long FileLength = in.readLong();
System.out.println("FileLength: "+FileLength);
File SharingPath = new File(SharingPathString);
if(!SharingPath.exists())
SharingPath.mkdir();
File outputFile = new File(FileName);
if(outputFile.exists())
outputFile.delete();
//outputFile.createNewFile();
FileOutputStream Fos = new FileOutputStream(FileName);
DataOutputStream dos = new DataOutputStream(Fos);
byte[] buffer = new byte[100];
int count=0;
long current=0;
while(current < FileLength && (count=in.read(buffer,0,(int)Math.min(FileLength-current, buffer.length)))!=-1)
{Fos.write(buffer, 0, count);
current+=count;
}
// while((count=in.read())!=-1)
// dos.write(count);
dos.close();
Fos.close();
} catch (UnknownHostException uhe) {
System.err.println(uhe);
} catch (IOException e) {
System.err.println(e);
}
}
}
You haven't read anything into bt[]. So you are writing the correct number of null bytes.

client server with multi threading

i write a program client-server with multi threading for send - receive file. The program runs and client send and server receive. the files are created but empty new files are created
Why? please help me
class client :
import java.io.*;
import java.net.Socket;
public class Client extends Thread {
Socket socket = null;
Socket socket1 = null;
public void sendFile() throws IOException {
String host = "127.0.0.1";
String host1 = "127.0.0.2";
socket = new Socket(host, 1024);
socket1 = new Socket(host1, 1025);
File file = new File("/home/reza/Desktop/link help");
File file1 = new File("/home/reza/Desktop/hi");
long length = file.length();
long length1 = file1.length();
final byte[] bytes = new byte[(int) length];
final byte[] bytes1 = new byte[(int) length1];
FileInputStream fis = new FileInputStream(file);
FileInputStream fis1 = new FileInputStream(file1);
#SuppressWarnings("resource")
final BufferedInputStream bis = new BufferedInputStream(fis);
final BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
#SuppressWarnings("resource")
final BufferedInputStream bis1 = new BufferedInputStream(fis1);
final BufferedOutputStream out1 = new BufferedOutputStream(socket1.getOutputStream());
Thread t = new Thread(new Runnable() {
public void run()
{
while(socket.isConnected())
{
Wait2();
try {
System.out.println("ok");
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
while(socket1.isConnected())
{
Wait2();
try {
System.out.println("ok1");
int count1;
while ((count1 = bis1.read(bytes1)) > 0) {
out1.write(bytes1, 0, count1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t.start();
socket.close();
socket1.close();
}
public void Wait2()
{
try {
Thread.sleep(3000);
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
class server:
import java.io.*;
import java.net.*;
public class Server {
public Server()
{
Thread t = new Thread(new Client());
t.start();
Thread t1 = new Thread(new Client());
t1.start();
}
//#SuppressWarnings("null")
public void recivefile() throws IOException {
ServerSocket serverSocket = null;
ServerSocket serverSocket1 = null;
try {
serverSocket = new ServerSocket(1024);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
try {
serverSocket1 = new ServerSocket(1025);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number1. ");
}
Socket socket = null;
Socket socket1 = null;
InputStream is = null;
InputStream is1 = null;
FileOutputStream fos = null;
FileOutputStream fos1 = null;
BufferedOutputStream bos = null;
BufferedOutputStream bos1 = null;
int bufferSize = 0;
int bufferSize1 = 0;
try {
socket = serverSocket.accept();
socket1 = serverSocket1.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
is = socket.getInputStream();
is1 = socket1.getInputStream();
bufferSize = socket.getReceiveBufferSize();
bufferSize1 = socket1.getReceiveBufferSize();
//bufferSize2 = socket2.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
System.out.println("file recieved");
System.out.println("Buffer size1: " + bufferSize1);
System.out.println("file recieved");
System.out.println("file recieved");
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream("/home/reza/Desktop/reza");
bos = new BufferedOutputStream(fos);
fos1 = new FileOutputStream("/home/reza/Desktop/ali");
bos1 = new BufferedOutputStream(fos1);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
}
public static void main(String[] args) throws IOException
{
System.out.println("server is run, please send file");
Server s = new Server();
s.recivefile();
}
}
client test class:
import java.io.IOException;
public class clientTest extends Thread {
public static void main(String[] args) throws IOException, InterruptedException
{
Client client = new Client();
client.sendFile();
}
}
I believe this code in the server to be your issue:
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
So the server has connected to the client, then it immediately checks to see if there are any bytes to read, if not it stops reading and closes the connection. If this happens faster than the client can deliver any bytes, boom, no data is received. And it WILL happend faster than the client can send data because the client is connecting THEN starting thread to send the data.
Instead, the server should read on each connection for as long as the client has maintained the connection alive. The server needs to wait for the data to be received.
Notice that in your code, the client is waiting for the server to close the connection. But how is the server supposed to know when all the data is sent? Either the client must close the connection or the client must send an EOF-type marker to the server indicating an end of the data and that it is safe to close the connection.

Categories

Resources