Why won't this work when sending an image file? - java

Server receives a file that the client sends.
When a text file is chosen, the transfer and the writing of the file is a success, but when an image file is chosen, either the transfer or the writing of the file generates some characters not found within the original file, thus corrupting the image file. Please help :)
public class Server {
private DatagramSocket socket = null;
private DatagramPacket inPacket;
private DatagramPacket outPacket = null;
private byte[] inBuffer, outBuffer;
private final int port = 50000;
private ChooseDestination cf = new ChooseDestination();
private BufferedWriter bw;
private int receivedNo = 1;
public static void main(String[] args) {
new Server();
}
public Server(){
this.connect();
}
public void connect(){
try{
socket = new DatagramSocket(port);
String fName = "";
while(true){
inPacket = null;
// waiting for input from client
inBuffer = new byte[1024];
inPacket = new DatagramPacket(inBuffer, inBuffer.length);
socket.receive(inPacket);
// get info of client
int source_port = inPacket.getPort();
InetAddress source_address = inPacket.getAddress();
System.out.println("Client: " + source_address + " Port:" + source_port);
// converts packets received to string for content checking
String data = new String(inPacket.getData(), 0, inPacket.getLength());
if(data.contains("filename")){
System.out.println("filename set");
fName = cf.browseFolders() + data.substring(8);
System.out.println("filename: " +fName);
outBuffer = new byte[1024];
outBuffer = ("ok").getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, source_address, source_port);
socket.send(outPacket);
}
if (data.endsWith("ERROR!")) {
System.out.println("File doesn't exist.\n");
socket.close();
}
else if (!(data.contains("filename"))){
File file = new File(fName);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileOutputStream fileOuputStream = new FileOutputStream(fName, true);
data = data.trim();
byte[] write = data.getBytes();
fileOuputStream.write(write);
fileOuputStream.close();
// sending acknowledgments formatted as ACKn where n is the packet received
outBuffer = new byte[1024];
outBuffer = ("ACK" + receivedNo + "").getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, source_address, source_port);
socket.send(outPacket);
receivedNo++;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
client sends the file to the server
public class Client {
private DatagramSocket socket = null;
private DatagramPacket inPacket;
private DatagramPacket outPacket = null;
private byte[] inBuffer, outBuffer;
private final int port = 50000;
private int packetNo = 1;
public Client(){
ChooseFile cf = new ChooseFile();
String fName = cf.BrowseFilesView();
this.sendFile(fName);
}
public static void main(String[] args) {
new Client();
}
public void sendFile(String fName){
try {
InetAddress address = InetAddress.getByName("192.168.1.15");
socket = new DatagramSocket();
Path path = Paths.get(fName);
byte[] data = Files.readAllBytes(path);
outBuffer = new byte[1024];
System.out.println(fName);
String[] tag = fName.split("\\\\");
System.out.println(tag[tag.length-1]);
outBuffer = ("filename"+tag[tag.length-1]).getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, address, port);
socket.send(outPacket);
String s = null;
int i = 0;
int orig = 0;
while(i < data.length){
i = orig;
byte[] send = new byte[1024];
for( int ii = 0; ii < 1024 && i < data.length; ii++, i++){
send[ii] = data[i];
}
outBuffer = new byte[1024];
outBuffer = send;
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, address, port);
socket.send(outPacket);
inBuffer = new byte[1024];
inPacket = new DatagramPacket(inBuffer, inBuffer.length);
socket.receive(inPacket);
String ack = new String(inPacket.getData(), 0, inPacket.getLength());
int ackNo = 0;
try{
ackNo = Integer.parseInt(ack.substring(3));
}
catch(Exception e){
e.printStackTrace();
}
if (packetNo == ackNo){
System.out.println(packetNo + " " + ackNo);
orig = i;
packetNo++;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Getting extra bytes in received file using java scoket

I have implemented a file transfer program using java socket. In this program, a file is sent from the client and its then downloaded in the Server. The program works almost correctly but the problem is the length of the received byte is always greater than the byte length sent from the client. for example, I sent 678888589 bytes from the client, but when I check the length of the received file at the server, I got 678925260 bytes. And for that reason, I am getting different checksum on the server side.
Here is my code:
Client Class:
public class Client
{
final static int ServerPort = 1234;
public static final int BUFFER_SIZE = 1024 * 50;
private static byte[] buffer;
public static void main(String args[]) throws UnknownHostException, IOException
{
Scanner scn = new Scanner(System.in);
buffer = new byte[BUFFER_SIZE];
for(int i=0;i<8;i++) {
Socket s1 = new Socket(ip, ServerPort);
DataOutputStream dos1 = new DataOutputStream(s1.getOutputStream());
SendMessage message = new SendMessage(s1, "test.mp4",dos1);
Thread t = new Thread(message);
System.out.println("Adding this client to active client list");
t.start();
}
}
}
class SendMessage implements Runnable{
String file_name;
Socket s;
public final int BUFFER_SIZE = 1024 * 50;
private byte[] buffer;
DataOutputStream dos;
public SendMessage(Socket sc,String file_name,DataOutputStream dos) {
this.file_name = file_name;
this.s=sc;
buffer = new byte[BUFFER_SIZE];
this.dos = dos;
}
#Override
public void run() {
File file = new File(file_name);
try {
sendFile(file, dos);
dos.close();
while(true) {
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void sendFile(File file, DataOutputStream dos) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE+1];
if(dos!=null&&file.exists()&&file.isFile())
{
FileInputStream input = new FileInputStream(file);
dos.writeLong(file.length());
System.out.println(file.getAbsolutePath());
int read = 0;
int totalLength = 0;
while ((read = input.read(buffer)) != -1) {
dos.write(buffer);
totalLength +=read;
System.out.println("length "+read);
}
input.close();
System.out.println("File successfully sent! "+totalLength);
}
}
}
Server Class
// Server class
public class Server
{
// Vector to store active clients
static Vector<ClientHandler> ar = new Vector<>();
// counter for clients
static int i = 0;
public static void main(String[] args) throws IOException
{
// server is listening on port 1234
ServerSocket ss = new ServerSocket(1234);
Socket s;
// running infinite loop for getting
// client request
while (true)
{
// Accept the incoming request
s = ss.accept();
System.out.println("New client request received : " + s);
// obtain input and output streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Creating a new handler for this client...");
// Create a new handler object for handling this request.
ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);
// Create a new Thread with this object.
Thread t = new Thread(mtch);
System.out.println("Adding this client to active client list");
// add this client to active clients list
ar.add(mtch);
// start the thread.
t.start();
// increment i for new client.
// i is used for naming only, and can be replaced
// by any naming scheme
i++;
}
}
}
// ClientHandler class
class ClientHandler implements Runnable
{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean isloggedin;
public static final int BUFFER_SIZE = 1024*50;
private byte[] buffer;
// constructor
public ClientHandler(Socket s, String name,
DataInputStream dis, DataOutputStream dos) {
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.isloggedin=true;
buffer = new byte[BUFFER_SIZE];
}
#Override
public void run() {
String received;
BufferedOutputStream out = null;
String outputFile = "out_"+this.name+".mp4";
BufferedInputStream in = null;
try {
in = new BufferedInputStream(s.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new BufferedOutputStream(new FileOutputStream(outputFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while (true)
// {
try
{
long length = -1;
length = dis.readLong();
if(length!=-1)System.out.println("length "+length);
// String checkSum = dis.readUTF();
// System.out.println(checkSum);
int len=0;
long totalLength = 0;
// int len = 0;
while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
out.write(buffer, 0, len);
totalLength+=len;
// if(len<BUFFER_SIZE)break;
// System.out.println("length "+len);
if(len<=0)break;
}
File file = new File(outputFile);
System.out.println("total length1 "+totalLength+ " dif "+(totalLength-length));
System.out.println("output length "+file.length());
} catch (IOException e) {
e.printStackTrace();
}
}
private static String checksum(String filepath, MessageDigest md) throws IOException {
// file hashing with DigestInputStream
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
while (dis.read() != -1) ; //empty loop to clear the data
md = dis.getMessageDigest();
}
// bytes to hex
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
It would be great if anyone can tell me what I am doing wrong. also, how can I verify the checksum on serverside. Another issue is the server side code get blocked in this block.
while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
out.write(buffer, 0, len);
System.out.println("length "+len);
if(len<=0)break;
}
It can't break the loop unless the client is disconnected. Although the file is recieved properly.
Regards.
You made a small mistake on the client code. You were writing out the full buffer instead of what is read from the file.
while ((read = input.read(buffer)) != -1) {
dos.write(buffer,0,read);
totalLength += read;
System.out.println("length " + read);
}

sending file using UDP multicast

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

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

UDP Sockets send and receive

I am trying to implement a UDP client server. The client is sending 1032 bytes using the rdt_send function but the server receives this packet only after the client is executed twice.
Here is the code for :
rdt_send:
public void rdt_send(byte[] buffer, Integer mss, DatagramSocket s,Integer seqNum) throws IOException
{
int i,j,k;
byte[] seq_num = new byte[4];
byte[] seqnum_temp = new byte[4];
byte [] checksum = new byte[2];
byte [] udp_field = new BigInteger("0101010101010101",2).toByteArray();
Integer checksum_value = (int)calculateChecksum(buffer);
checksum = new BigInteger(checksum_value.toString(), 10).toByteArray();
seqnum_temp = new BigInteger(seqNum.toString(),10).toByteArray();
System.out.println(checksum_value);
Integer length_temp = seqnum_temp.length;
if (seqnum_temp.length<4)
{
Integer append = 4 -seqnum_temp.length;
for (i=0;i<append;i++)
{
seq_num[i] = 0;
}
for (j = append, k=0 ; j<4 && k<length_temp ; j++,k++)
{
seq_num[j] = seqnum_temp[k];
}
System.out.println(seq_num[0]);
}
byte[] finalSend = new byte[mss+8];
for (i=0;i<4;i++)
{
finalSend[i] = seq_num[i];
}
for (i=4,k=0;i<6 && k<2;i++,k++)
{
finalSend[i] = checksum[k];
}
for (i=6,k=0;i<8 && k<2 ;i++,k++)
{
finalSend[i] = udp_field[k];
}
for (i=8,k=0;i<finalSend.length && k< buffer.length;i++,k++)
{
finalSend[i] = buffer[k];
}
for (i=0;i<finalSend.length;i++)
{
System.out.println(finalSend[i]);
}
System.out.println("Got to final sending stage");
DatagramPacket p = new DatagramPacket (finalSend,finalSend.length,InetAddress.getLocalHost(),7771);
s.send(p);
System.out.println("Sent datagram");
}
client :
package simpleFTP;
public class SimpleFTPClient {
public static void main(String args[]) throws IOException{
Integer seq_num =512;
Utils u = new Utils();
DatagramSocket d = new DatagramSocket();
File f =new File("C:/Users/amoolp/Desktop/client3/3333.txt");
FileInputStream fs = new FileInputStream(f);
byte[] bytesRead = new byte[1024];
fs.read(bytesRead,0,1024);
//DatagramPacket p = new DatagramPacket (bytesRead,bytesRead.length,InetAddress.getLocalHost(),7771);
// d.send(p);
u.rdt_send(bytesRead,1024,d,seq_num);
}
}
Server :
public class Server {
public static void main (String args[]) throws IOException
{
DatagramSocket dg = new DatagramSocket (7771);
byte[] buf = new byte[1032];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
System.out.println("Waiting to receive packet");
dg.receive(packet);
System.out.println("Received packet");
for (int i=0; i<buf.length ; i++)
{
System.out.println(buf[i]);
}
}
}
Any ideas as to why this is happening?
It's due to the buffer. flush() the socket after sending a packet.

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();

Categories

Resources