I am trying to send file from java app to a remote c# application through socket
here is the code
C#
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ip, 1593);
NetworkStream networkStream = tcpClient.GetStream();
StreamReader sr = new StreamReader(networkStream);
//read file length
int length = int.Parse(sr.ReadLine());
byte[] buffer = new byte[length];
networkStream.Read(buffer, 0, (int)length);
//write to file
BinaryWriter bWrite = new BinaryWriter(File.Open(strFilePath, FileMode.Create));
bWrite.Write(buffer);
bWrite.Flush();
bWrite.Close();
tcpClient.Close();
Java app
ServerSocket serverSocket = new ServerSocket(1593);
System.out.println("Server started and waiting for request..");
Socket socket = serverSocket.accept();
System.out.println("Connection accepted from " + socket);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
File file = new File(strFileToSend);
// send file length
out.println(file.length());
// read file to buffer
byte[] buffer = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.read(buffer, 0, buffer.length);
// send file
BufferedOutputStream bos = new BufferedOutputStream(
socket.getOutputStream());
bos.write(buffer);
bos.flush();
serverSocket.close();
System.out.println("File has been send ... ");
The exception raised from the client side
Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host
The server application said it has sent successfully the file.
Thanks in advance.
Your problem is that you are issuing serverSocket.close(); too soon. The Server Socket is not supposed to be closed just because a single transaction between the client and the server concluded. The server socket is supposed to stay open for as long as the server is running.
So, when you close the server socket, the response to the client is still in transit, (it probably hasn't even begun transmitting yet from the server to the client,) so the client gets disconnected prematurely, before it has had the chance to receive or fully process the response.
Related
Currently trying to send and receive some data via TCP connection using java socket,
creating socket like this:
socket = new Socket();
socket.setSoTimeout(soTimeout > 0 ? soTimeout : DEFAULT_SOCKET_TIMEOUT);
socket.setSendBufferSize(1);
socket.connect(new InetSocketAddress(address, port), connectTimeout > 0 ? connectTimeout : DEFAULT_CONNECT_TIMEOUT);
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
And trying to write data and read response like this:
try {
os = getPort().getOutputStream();
bos = new BufferedOutputStream(os);
is = getPort().getInputStream();
bis = new BufferedInputStream(is);
bos.write(result);
bos.flush();
os.flush();
byte [] reply = new byte[5];
is.read(reply);
} catch (Exception ex) {
throw new RuntimeException("Failed to send data: ", ex.getMessage());
}
field result being byte array, b
Exact same data send via UTP works perfectly, but trying to send it via TCP always ends up with ReadTimeoutException,
there are logs saying that connection is set on the target server, but no logs about received data
Can you maybe give me some hints on what could be the reason?
I am trying to code a java socket server to send an image from this server to the navigator(client side). But when I send the image the file seen to be corrupted (display the image with symbols).
DataOutputStream dout = new DataOutputStream(connectS.getOutputStream());
String file="image.jpg";
File filename = new File(file);
FileInputStream fin = new FileInputStream(filename);
//dout.writeUTF(file);
System.out.println("Sending image...");
int size=(int) filename.length();
byte[] readData = new byte[size];
fin.read(readData);
dout.writeInt(size);
dout.flush();
dout.write(readData,0,size);
/*for(int i=0;i<readData.length;i++) {
dout.write(readData, 0, i);
}*/
dout.flush();
Here is how I start the program
ServerSocket ss=new ServerSocket(8080);
Socket connectS=ss.accept();
BufferedReader in=new BufferedReader(new InputStreamReader(connectS.getInputStream()));
Thanks for your help!!!
I solved the problem.
First, remove dout.readInt();
Then, open microsoft edge;(mozilla shows the image but there seems to be an encoding issue,that's my opinion,maybe not the true);
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 3 years ago.
I'm using Java Socket to send a file to server and then get a response back. The problem is every time i try to read the response from server, it makes the file-reading part of the server hang. I really need your help on what's going on here?
Here is SERVER code:
ServerSocket server = new ServerSocket(PORT);
Socket client = server.accept();
BufferedInputStream netInStream = new BufferedInputStream(client.getInputStream());
BufferedOutputStream netOutStream = new BufferedOutputStream(client.getOutputStream());
String outFileName = "output/test";
File outputFile = new File(outFileName);
if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs();
}
FileOutputStream fileOutStream = new FileOutputStream(outputFile);
BufferedOutputStream bufOutStream = new BufferedOutputStream(fileOutStream);
// read file from client and save
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = netInStream.read(buffer)) > 0) {
bufOutStream.write(buffer, 0, bytesRead);
bufOutStream.flush();
Log.line("Bytes read: " + bytesRead);
}
// clean up file IO
// ...
// send response to client
netOutStream.write("File received by server".getBytes());
netOutStream.flush();
// clean up network IO
// ...
CLIENT code:
Socket client = new Socket(DOMAIN_SERVER, PORT_SERVER);
BufferedOutputStream netOutStream = new BufferedOutputStream(client.getOutputStream());
BufferedInputStream netInStream = new BufferedInputStream(client.getInputStream());
String inFileName = "input/test";
File file = new File(inFileName);
if (!file.exists()) {
client.close();
return;
}
FileInputStream fileInSream = new FileInputStream(file);
BufferedInputStream bufInStream = new BufferedInputStream(fileInSream);
// read and send file to server
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = bufInStream.read(buffer)) > 0) {
netOutStream.write(buffer, 0, bytesRead);
netOutStream.flush();
Log.line("Bytes sent: " + bytesRead);
}
// clean up file IO
// ...
// read response from server
StringBuilder res = new StringBuilder();
byte[] charBuf = new byte[128];
int msgBytesRead = 0;
while ((msgBytesRead = netInStream.read(charBuf)) > 0) {
res.append(new String(charBuf, 0, msgBytesRead));
}
Log.line(res.toString());
// clean up network IO
// ...
The flow is, client sends a file to server, server reads the file and saves to its local storage then the server sends a response string to client, the client reads the response and prints it out on the screen.
If the code is like above, the server will not exit the while-loop and hang, therefor the client second while-loop doesn't read anything and hang, too.
But if i comment/remove the client second while-loop, both programs run and no hang occurs. File transfer is also success.
Your expectation is that read returns with no data once the server is done sending the file. This expectation is wrong. read will only return with no data if the server has closed the TCP connection and the flush you show does not close the connections but only makes sure that all buffered data are written to the TCP connection.
This means the server can still send more data after the flush and that's why your client is hanging in the read and waiting for more data.
I am writing Socket program , Here Client Sends a String through Stream , Server Process it and writes back to Client. My problem is, after Server process the String , it Writes back to Stream but in client It can't able to read the Stream its showing exception as Exception in while: java.net.SocketException: socket closed Here is my code,
Client ,
public void run() {
while (true) {
try {
// Open your connection to a server, at port 1231
s1 = new Socket("localhost", 1231);
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
InputStream in=s1.getInputStream();
DataInputStream dis=new DataInputStream(in);
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
dos.close();
System.out.println(dis.readUTF());//it is the String from Server after processing
dis.close();
} catch (IOException ex) {
// Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Exception in while: " + ex);
}
}
In Server
public void run()
{
while(true){
try {
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
String clientData=dis.readUTF();
//processing task String
dos.writeUTF("Bus Registered Successfully");
dos.flush();
}
}
Here I am not able to read Bus Registered Successfully at client side . How to Solve this.?
Well there are many things not right in your program. But first let me answer your question ... you are closing the socket just after writing the stream ... so server throws exception, just remove dos.close(); just after the dos.flush();. It will run fine.
Now back to the programming practices ...
1) Server should accept the connection in a while(true) loop and then make a new thread. So following statement should not be the part of run method.
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
2) There is no need of run method in client. Because Every new client will be a new program that has its own variables and socket.
A quick look shows me that the reason the socket is closed is because you used dos.close().
Closing a DataInputStream (or PrintStream, or any similiar stream) will close the underlying socket.
Just take out dos.close().
You can also move the dos.close() to the very end of the try block. As a general rule, don't close anything related to the socket until you're done with the socket.
I am working on transferring a file between two computers over a socket. Everything seems to work, but when I look at the contents of the retrieved file, it is empty. What am I doing wrong?
Here is my server-side code. The file foobar.txt exists, and its contents are "hello world!".
try{
ServerSocket ssock = new ServerSocket(12345);
Socket sock = ssock.accept();
//here I get the filename from the client, but that works fine.
File myFile = new File("foobar.txt");
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
} catch (Exception e){
e.printStackTrace();
}
And here is my client code:
try {
Socket socket = new Socket(host, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.print("get foobar.txt\r\n");
out.flush();
byte[] streamIn = new byte[1024];
InputStream in = socket.getInputStream();
FileOutputStream file_src = new FileOutputStream("foobar.txt");
BufferedOutputStream file_writer = new BufferedOutputStream(file_src);
int i;
while ((i = in.read()) != -1) {
file_writer.write(i);
}
file_writer.flush();
file_writer.close();
file_src.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
Solved
Since I am using multiple threads and multiple sockets and testing all connections on one machine, I was simply running into a problem where the client (which has both the client and server code in it) would connect with itself instead of the other client. Changing the file transfer port for the different running clients got this all to work. Thanks for everyone who had a look at this and gave me some suggestions.
Maybe you're closing the wrong socket on the client. When you close the socket, you're closing the class field this.socket instead of the local variable socket.
Also, when you close the output stream to the file, you don't have to close both the BufferedOutputStream and the FileOutputStream. The FileOutputStream is automatically closed when the BufferedOutputStream is closed.
One more thing---you don't have to flush an output stream before closing it. When you call close() the stream is automatically flushed.
In addition to what everyone else has said, you are ignoring the result of bis.read(). It isn't guaranteed to fill the buffer. See the Javadoc.
The correct way to copy streams in Java, which you should use at both ends, is this:
byte[] buffer = new byte[8192]; // or whatever
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
The only thing I think of that is that you actually never start receiving the file because the server-side doesn't read the command ("get foobar.txt"), so the client-side freezes on sending the command.
The existence of the file at the client-side might be from previous tests.
But, I'm not sure this is the problem. It's just a try to help.