sending file from Java to c# exception found - java

I try to send a java application file to a .Net application (c #) using a socket. Here is what I did Java (server side)
ServerSocket serverSocket = new ServerSocket(1592);
Socket socket = serverSocket.accept();
System.out.println("Connection accepted from " + socket);
PrintWriter out = new PrintWriter(socket.getOutputStream());
File file = new File("C:\\test.txt");
Thread.sleep(2000);
out.println(file.length());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = socket.getOutputStream();
byte[] bytes = new byte[(int) file.length()];
bis.read(bytes, 0, bytes.length);
os.write(bytes, 0, bytes.length);
C#(client)
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ip, 1592);
using (var stream = tcpClient.GetStream())
using (var output = File.Create("result.txt"))
{
Console.WriteLine("Client connected. Starting to receive the file");
// read the file in chunks of 1KB
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)//(Exception caught here)
{
output.Write(buffer, 0, bytesRead);
}
I had an exception in the specified line containing the following problem
Additional information: Unable to read data from the transport connection: Une connexion existante a dû être fermée par l’hôte distant.
Please any help , i've been facing the issue since few days , and i could not figure it out .
Thank you in advance

The Client is running, but the service is not available. (stopped, crashed..). Perhaps, the Firewall block the connection
Verify that the firwall not blocking your server
You must debug you code and verify its behavior (exception, etc..)
regards

Related

How to send either String or File through android socket?

I just realized that DataInputStream and DataOutputStream in writing reading socket
could be used to differentiate the input that was coming over.
Check this code:
Server Side. (receiving string or file)
Socket bSock = serverSocket.accept();
DataInputStream inp = new DataInputStream(bSock.getInputStream());
int iCode = inp.readInt();
switch (iCode) {
case Request.STATE_FILESHARING:
byte bp[] = new byte[iCode];
FileOutputStream fos = new FileOutputStream("s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = inp.read(bp, 0, bp.length);
bos.write(bp, 0, bytesRead);
bos.close();
break;
case Request.STATE_CONVERSATION:
requestFound = new Request(inp.readUTF());
sendToUI(requestFound);
break;
}
Client Side. (sending string or file)
Socket socket = new Socket(myServerAddress, SocketServerPORT);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
if (isThisFileMode()) {
File myFile = new File(sLocationFile);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
out.writeInt(Request.STATE_FILESHARING);
out.write(mybytearray, 0, mybytearray.length);
out.flush();
} else {
out.writeInt(Request.STATE_CONVERSATION);
out.write(obReq.toString().getBytes());
out.flush();
}
But I ended up with Error. System crashed!
Anything that I forgot to add?
You're using readUTF() but not writeUTF(). Nearly all the methods of DataInputStream and DataOutputStream are symmetrical: if you call readXXX() you must call writeXXX() at the other end.
You're making the usual mistake of assuming that read() fills the buffer. It is only contracted to transfer at least one byte. You must loop:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
You need to close the socket at both server and client.

java socket programming to send and receive file between two machines

I am trying to communicate between two machines using socket programming.
What I basically need is both machines should be able to send and receive files. The code I am pasting below is not showing any error but the server side program seems to be running indefinitely, i.e., it is not terminating. It got stuck on the line marked with comment stuck here.
In this code, initially, server is sending the file named "file.txt" and client is receiving it and saving the file with name "copy.txt". Later client is sending a file named "file2.txt" and server is receiving and saving it with name "copy2.txt".
Can someone please tell me the error and suggest some improvements?
//server side code
import java.net.*;
import java.io.*;
public class server
{
public static void main (String [] args ) throws IOException
{
//sending file started
ServerSocket serverSocket = new ServerSocket(16167);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File ("/Users/abhishek/desktop/file.txt");
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();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
System.out.println("File transfer complete");
//socket.close();
//sending comleted
//receiving file started
int filesize=1022386;
int bytesRead=0;
int currentTot = 0;
byte [] bytearray1 = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy2.txt");
//fos.flush();
BufferedOutputStream bos = new BufferedOutputStream(fos);
//bos.flush();
System.out.println("not moving ahead!!!");//program stucked here
bytesRead = is.read(bytearray1,0,bytearray1.length);
currentTot = bytesRead;
System.out.println("current"+currentTot);
do
{
bytesRead = is.read(bytearray1, currentTot, (bytearray1.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
System.out.println("current"+currentTot);
} while(bytesRead > -1);
System.out.println("outside current"+currentTot);
bos.write(bytearray1, 0 , currentTot);
bos.flush();
//receiving complete
System.out.println("Receving file completed");
socket.close();
}
}
//client side code
import java.net.*;
import java.io.*;
public class client
{
public static void main (String [] args ) throws IOException
{
int filesize=1022386;
int bytesRead=0;
int currentTot = 0;
Socket socket = new Socket("localhost",16167);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy.txt");
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);
System.out.println("current"+currentTot);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
System.out.println("receiving first file completed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//sending file
System.out.println("sending second file started!");
File transferFile = new File ("/Users/abhishek/desktop/file2.txt");
byte [] bytearray2 = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray2,0,bytearray2.length);
OutputStream os = socket.getOutputStream();
os.flush();
os.write(bytearray2,0,bytearray2.length);
os.flush();
System.out.println("sending second file completed!");
//sending complete
socket.close();
}
}
Does the System.out.println("not moving ahead!!!");//program stucked here line actually execute? if so, then the problem is that the InputStream.read() functions are blobking functions; they will stop execution of the program ("block") until they are able to complete.
From the JavaDoc for InputStream:
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.
This method blocks until input data is available, end of file is detected, or an exception is thrown.
Since you aren't getting an exception, this means that when you call .read(), there is no data available to be read, and you program sits around waiting for data to read (that never arrives). You should check that your client program is actually sending the data in the first place.
I'd bet
bytesRead = is.read(bytearray1,0,bytearray1.length);
is where you're really getting stuck. The problem normally if you are stuck here is that the other side of the communication has not sent any data, there's nothing to read, and your thread is stuck waiting for it to send.
on your client side, you call
bos.close();
after sending the first message. This is going to cause the socket to close as well, which will throw an IOException on your server end, and because you are not catching the IOException, your server program will just exit.
How much socket experience do you have? If you are just beginning with sockets, you might want to check out the extensions I wrote around this, starting with ServerSocketEx and DataFetcher.

Sending a file using sockets (java) from a client to the server succeeds but the client freezes and does not exit the loop

I run the server and client on separate cmd windows. The server prints out "Upload successful" and indeed the file gets uploaded to the server but the client freezes and i have to quit the client process using Ctrl+C. It seems to me that the client cannot break out of the while loop. Please tell me where i am going wrong?
(The code snippets are parts of much larger code body that i am writing to implement file read, write, read/write-lock, delete file etc from the server. Once a request to upload the file from the client is handled by the server I want the process to return to the command line menu i have incorporated with the client program[not shown below]. So it is important that the client returns to that user interface. Any help is greatly appreciated. Thanks in advance! )
Client side:
// initialized client and server connection made...
BufferedReader filePath = new BufferedReader(new InputStreamReader(System.in));
String pathname = filePath.readLine();
try{
File file_to_upload = new File(pathname);
byte[] bytearray = new byte[(int) file_to_upload.length()];
OutputStream os = client1.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file_to_upload));
do {
bis.read(bytearray, 0, bytearray.length);
os.write(bytearray, 0, bytearray.length);
os.flush();
bis.close();
} while (bis.read(bytearray, 0, bytearray.length)!= -1);
}
catch(FileNotFoundException e){
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
}
System.out.println("\n" + inFromServer.readLine() + "\n");
client1.close();
break;
server side:
byte[] mybytearray = new byte[1];
InputStream is = server1accept.getInputStream();
FileOutputStream fos = new FileOutputStream("234rews");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
outToClient.writeBytes("Uploaded");
System.out.println("Upload Successful");
Both your copy loops are incorrect. The canonical way to copy between streams in Java is:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
At present you are doing extra reads and ignoring read() results and all kinds of other strange things. Use this code at both ends, with any buffer size greater than zero.

InputStream read() method never returns -1 (Java)

I am trying to send Files with JAVA. My problem is that the client never knows if the end of the file is reached or not. So the while loop of the Client never ends. Please help me.
Server (sends Data to Client)
File myFile = new File("C://LEGORacers.exe");
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = null;
OutputStream os = null;
bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
os = socket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
Client (gets Data from Server)
byte[] buf = new byte[1024];
InputStream is = null;
int bytesRead = 0;
is = client.getInputStream();
FileOutputStream fos = null;
fos = new FileOutputStream("C://copy.exe");
BufferedOutputStream bos = new BufferedOutputStream(fos);
try {
while (-1 != (bytesRead = is.read(buf, 0, buf.length))) {
// This while loop never ends because is.read never returns -1 and I don't know why...
bos.write(buf, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
is.close();
bos.flush();
bos.close();
fos.close();
}
Did you close your OutputStream on your Server? If not, your loop might be perpetually setting bytesRead to 0, so you may need to close that stream.
If you need the Server's OutputStream to still be open after sending data, you could also send the size of the data in bytes at the beginning of the stream, and loop until you have all of the bytes the Server indicates it will send.
Close the socket output stream on the server. Flushing doesn't terminate the stream, which is what you need to do to send the signal that the server is done writing. From what you posted, I don't see where you close the output stream on the server side.

Socket transferring a file

I have a Java server class like this:
ServerSocket servsock = new ServerSocket(63456);
boolean read = false;
while (!read) {
Socket sock = servsock.accept();
int length = 1024;
byte[] mybytearray = new byte[length];
OutputStream os = sock.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
while (true) {
int i = bis.read(mybytearray, 0, mybytearray.length);
if (i == 1) {
break;
}
os.write(mybytearray, 0, mybytearray.length);
os.flush();
}
sock.close();
read = true;
}
`
And the client is like this:
Socket sock = new Socket("127.0.0.1", 63456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:/tmp/NEWtmp.rar");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
while(bytesRead != -1 ) {
bos.write(mybytearray, 0, bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
}
bos.close();
sock.close();
One question is: Why the loop does not stop at the end of the file?
A second question would be, why is also so slow?
It does not stop because
if (i == 1) {
in your server source should be
if (i == -1) {
Or, if you want to be really safe:
if (i <= 0) {
Also, you risk data corruption with this line:
os.write(mybytearray, 0, mybytearray.length);
You should change this to:
os.write(mybytearray, 0, i);
On performance -- move the os.flush(); call to outside the while loop. When you flush a network stream, you are forcing it to dispatch any buffered data to the network. This is forcing the network layer to send and acknowledge 1024-byte TCP payloads (larger Ethernet payloads, of course) which is probably significantly smaller than your PMTU. You only need to flush when you are done sending data, or when you want the client to receive the buffered data now. Removing the flush call from each iteration will allow the OS-level network buffer to do its job, and segment the data into as few packets as possible.
Second question - your client reads bytes directly from the raw socket stream. Use the BufferedInputStream/BufferedOutputStream decorators, this should increase performance:
Server Side
BufferedOutputStream os = new BufferedOutputStream(sock.getOutputStream());
Client side
BufferedInputStream is = new BufferedInputStream(sock.getInputStream());
The raw streams are not buffered (AFAIK) so you have to add the buffering manually, if needed.

Categories