I'm kind of new to Android and I have a task to open a TCP socket and listen to a specific port.
A client application is supposed to send me 2 images and a string that are related to each other so instead of sending each data alone we thought about putting all data in a json object and send this object.
My question is, how do I parse this json into saving 2 images and a string?
So this json is supposed to be like this:
data
{
FileName: "some string",
Image1: "Image encoded with encode base64",
Image2: "Image encoded with encode base64"
}
I'm using an AsyncTask so here is the code where I get the socket data:
public class DataRecord
{
String Image1;
String Image2;
String FileName;
}
protected DataRecord doInBackground(Socket... sockets) {
DataRecord dataRecord = null;
if (isExternalStorageWritable() && sockets.length > 0) {
Socket socket = sockets[0];
dataRecord = socket.getOutputStream(); // how to extract the data from the socket into this object ???
File file = new File(Environment.getExternalStorageDirectory(), dataRecord.FileName);
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream inputStream;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
inputStream.read(bytes, 0, bytes.length);
OutputStream outputStream = dataRecord.Image1;
outputStream.write(bytes, 0, bytes.length);
outputStream.flush();
socket.close();
}
catch (Exception e) { }
finally {
try {
socket.close();
} catch (IOException e) { }
}
}
return dataRecord;
}
And I need to get it from the socket object and extract an object from it to save the 2 images to the SD card and extract the string to the UI.
I know this question probably have more than one answer, but still posting an answer is a good idea.
So, I found this link here A Simple Java TCP Server and TCP Client which helped me getting started with my solution.
I've also used Gson to parse my JSON string using this nice tutorial: Android JSON Parsing with Gson Tutorial.
Finally, my code looks like this:
ServerSockerThread.java - this is the java class for the listening server which waits for incoming files:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketThread extends Thread {
static final int SocketServerPORT = 6789;
ServerSocket serverSocket;
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
socket = serverSocket.accept();
new FileSaveThread().execute(socket);
}
}
catch (IOException e) { }
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) { }
}
}
}
protected void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
}
catch (IOException e) { }
}
}
}
FileSaveThread.java - this is the java class that is being called by the above server class for each incoming file:
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Socket;
public class FileSaveThread extends AsyncTask<Socket, Void, DataRecord> {
#Override
protected void onPostExecute(DataRecord dataRecord) {
super.onPostExecute(dataRecord);
}
#Override
protected DataRecord doInBackground(Socket... sockets) {
DataRecord dataRecord = null;
if (isExternalStorageWritable() && sockets.length > 0) {
Socket socket = sockets[0];
try {
Gson gson = new Gson();
Reader reader = new InputStreamReader(socket.getInputStream());
SocketObject socketObject = gson.fromJson(reader, SocketObject.class);
SaveFileToSDCard(socketObject.Image1, "Image1.png");
SaveFileToSDCard(socketObject.Image2, "Image2.png");
SaveFileToSDCard(socketObject.Image3, "Image3.png");
dataRecord = new DataRecord(socketObject.Name);
}
catch (Exception e) { }
finally {
try {
socket.close();
} catch (IOException e) { }
}
}
return dataRecord;
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private void SaveFileToSDCard(String base64String, String fileName) throws IOException {
byte[] decodedString = Base64.decode(base64String.getBytes(), android.util.Base64.DEFAULT);
File file = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file, false);
fileOutputStream.write(decodedString);
fileOutputStream.close();
fileOutputStream.flush();
}
}
Related
I have to do a project in Java for an exam which has to have multi-client sockets.
We have some example code for sockets from our teacher - and I modified it a bit. The problem is that it only receives data once, and then it stops. I found that out by printing the received data into the console.
So here's my the code:
Server.java
package socket;
import database.models.PersoanaEntity;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 27015;
public void start() {
new Thread(() -> {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = null;
boolean isClose = false;
System.out.println("Server is running");
while (!isClose) {
clientSocket = serverSocket.accept();
new Thread(new ServerThread(clientSocket)).start();
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
ServerThread.java
package socket;
import database.models.PersoanaEntity;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket socket = null;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
PersoanaEntity loggedInPerson = new PersoanaEntity();
public ServerThread(Socket socket) {
this.socket = socket;
try {
//For receiving and sending data
this.in = new ObjectInputStream(socket.getInputStream());
this.out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String received = this.in.readObject().toString();
System.out.println(received);
JSONObject jsonObject = new JSONObject(received);
execute(received);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void execute(String message) {
JSONObject jo = new JSONObject(message);
ProcessInput pi = new ProcessInput();
pi.processInput(jo, this.out);
}
}
ProcessInput.java
package socket;
import database.daos.PersoanaDao;
import database.models.PersoanaEntity;
import jakarta.persistence.NoResultException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Optional;
public class ProcessInput {
void processInput(JSONObject data, ObjectOutputStream out) {
switch (data.get("type").toString())
{
case "LOGIN_USER":
PersoanaDao persoanaDao = new PersoanaDao();
String username = data.get("username").toString();
JSONObject json = new JSONObject();
try {
PersoanaEntity persoanaEntity = persoanaDao.get(username);
json.put("status_code", "200");
} catch(Exception e) {
json.put("status_code", "404");
}
try {
out.writeObject(json.toString());
} catch (IOException e)
{
System.out.println(e.toString());
}
break;
}
}
}
I won't add the code from the client side because I'm quite sure the problem is from the server after doing some tests. I think that it happens because the run method is only called once, AFAIK, and that is when .start() is called from the Thread.
Then it won't ever be called again so there will never be data in the received string.
Am I right?
If so, what's the fix?
If not, why am I getting data only once and how can I fix it?
//edit: I will add the client just in case:
package socket;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public enum Client implements Runnable {
INSTANCE;
public static final int PORT = 27015;
public Socket getSocket() {
return socket;
}
public ObjectInputStream getInputStream() {
return inputStream;
}
public ObjectOutputStream getOutputStream() {
return outputStream;
}
private Socket socket = null;
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
private String name;
Client() {
try {
socket = new Socket("localhost", PORT);
this.outputStream = new ObjectOutputStream(socket.getOutputStream());
this.inputStream = new ObjectInputStream(socket.getInputStream());
} catch(Exception e) {
System.out.println("Connection error");
}
}
public void run() {
System.out.println("Client socket running");
//For receiving data
boolean isClose = false;
while (!isClose) {
}
try {
socket.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I can't add a ObjectInputStream to read input from the user, it always blocks at that point. This code works fine if I remove the ObjectInputStream in the Server that is supposed to read input from user and then send hardcoded String instead. What is happening behind the scenes? I'am aware that when a ObjectOutputStream is created it sends a header and when a ObjectInputStream is created it reads that header. Do I need to flush something in System before I try to instantiate oOISUser?
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server() {
ServerSocket oSS = null;
Socket oS = null;
ObjectOutputStream oOOS = null; // to write to socket
ObjectInputStream oOIS = null; // to read from socket
ObjectInputStream oOISUser = null; // to read input from user
try {
oSS = new ServerSocket(1025);
oS = oSS.accept();
oOOS = new ObjectOutputStream(oS.getOutputStream());
oOIS = new ObjectInputStream(oS.getInputStream());
oOISUser = new ObjectInputStream(System.in);`// doesn't get past this
String sToSend = (String) oOISUser.readObject();
System.out.println("server says: " + sToSend);
oOOS.writeObject(sToSend);
oOOS.flush();
System.out.println("server receives: " + (String) oOIS.readObject());
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} finally {
try {
if (oSS != null) oSS.close();
if (oS != null) oS.close();
if (oOOS != null) oOOS.close();
if (oOIS != null) oOIS.close();
if (oOISUser != null) oOISUser.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
Server s = new Server();
}
}
This is the code for the Client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Client {
public Client() {
Socket oS = null;
ObjectOutputStream oOOS = null;
ObjectInputStream oOIS = null;
try {
oS = new Socket("127.0.0.1", 1025);
oOOS = new ObjectOutputStream(oS.getOutputStream());
oOIS = new ObjectInputStream(oS.getInputStream());
System.out.println("client receives: " + (String) oOIS.readObject());
String sToSend = "hello from client";
System.out.println("client says: " + sToSend);
oOOS.writeObject(sToSend);
oOOS.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} finally {
try {
if (oS != null) oS.close();
if (oOOS != null) oOOS.close();
if (oOIS != null) oOIS.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
Client c = new Client();
}
}
new ObjectInputStream(System.in)
You said it yourself in the question:
when a ObjectInputStream is created it reads that header
So you're effectively waiting for the user to enter an ObjectInputStream header in the console. That has a very very tiny chance to happen (unless a file is piped to System.in). It just makes very little sense to read serialized Java objects from System.in. The user can't possibly type valid serialized Java objets in the console. He/She can type text, though. So use a Reader or a Scanner.
I'm trying to develop a simple Java file transfer application using TCP.
My current server code is as follows:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
new FTPServer().go();
}
void go() {
try {
ServerSocket server = new ServerSocket(2015);
System.out.println("server is running ....!");
while (true) {
Socket socket = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String file = reader.readLine();
System.out.println("file to be downloaded is : " + file);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
//bos.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Using my current server code above, the downlloding does not work as expected. the above code sends part of the file to the client , not the entire file. Note that I used the flush method to flush the buffer. but when I replace the flush () method by the close () method, the file is fully sent to the client whithout any loss. Could anyone please explain this behavior!
UPDATE: Here is the code of my client:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* #author aaa
*/
public class FTPClient {
public static void main(String[] args) {
String file = "JasperReports-Ultimate-Guide-3.pdf";
try {
InetAddress address = InetAddress.getLocalHost();
Socket socket = new Socket(address, 2015);
System.out.println("connection successfully established ....!");
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println(file);
pw.flush();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy" + file));
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
System.out.println("file download is complete ...!");
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Another behavior without the use of Socket. take the following code that copy a file from a source to a destination:
public class CopieFile {
static void fastCopy(String source, String destination) {
try {
FileInputStream fis = new FileInputStream(source);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(destination);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) throws IOException {
String source = "...";
String destination = "...";
fastCopy(source, destination);
}// end main
}// end class
the above code to copy a file from one location to another without any loss. Note well that I did not close the stream.
If you never close the stream the client wil never get end of stream so it will never exit the read loop.
In any case the stream and the socket are about to go out of scope, so if you don't close them you have a resource leak.
I have a Client-Server programm. The Client-programm sends a file to the server and the server receives the file. my problem is, that the file is not really receiving on the server...I't creates a file.txt in the server-directory, but it is empty...(yes i'm sure that ne file.txt in the client-directory is not empty ;) )
I think the problem is the while-loop in Client.java, because it is never embarrassed....
For the future i implements now on the server side one thread per receiving file.
The client-programm:
package controller;
public class Main {
public static void main(String[] args) {
new Controller();
}
}
-
package controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Controller {
public Controller() {
try {
sendFileToServer();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFileToServer() throws UnknownHostException, IOException {
Socket socket = null;
String host = "localhost";
socket = new Socket(host, 5555);
String filename = "file.txt";
File file = new File(filename);
OutputStream outText = socket.getOutputStream();
PrintStream outTextP = new PrintStream(outText);
outTextP.println(filename);
long filesize = file.length();
byte[] bytes = new byte[(int) filesize];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
System.out.println("Start sending file...");
while ((count = bis.read(bytes)) > 0) {
System.out.println("count: " + count);
out.write(bytes, 0, count);
}
System.out.println("Finish!");
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
-
The server-programm:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
new Server();
}
}
-
public class Server {
private ServerSocket serverSocket;
public Server() {
try {
serverSocket = new ServerSocket(5555);
waitForClient();
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForClient() {
Socket socket = null;
try {
while(true) {
socket = serverSocket.accept();
Thread thread = new Thread(new Client(socket));
thread.start();
}
} catch (IOException ex) {
System.out.println("serverSocket.accept() failed!");
}
}
}
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client implements Runnable{
private Socket socket;
public Client(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
receiveFile();
}
private void receiveFile() {
try {
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
InputStream outText = socket.getInputStream();
// Get filename
InputStreamReader outTextI = new InputStreamReader(outText);
BufferedReader inTextB = new BufferedReader(outTextI);
String dateiname = inTextB.readLine();
System.out.println("Dateiname: " + dateiname);
try {
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream(dateiname);
bos = new BufferedOutputStream(fos);
} 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);
System.out.println("This is never shown!!!"); // In this while-loop the file is normally receiving and written to the directory. But this loop is never embarrassed...
}
bos.flush();
bos.close();
is.close();
socket.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
When you do these kind of transfers you have to keep in mind that there is a difference between a socket's close and shutdown, in your code you close the socket in the client.
So lets see what happens : you fill in the buffers then you tell the socket to close which will discard the operation you just asked for.
When you shutdown you tell the socket "I won't send more data but send what's left to be sent and shut down" so what you need to do is to shut down the socket before you close it so the data will arrive.
So instead of this
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
Try it with this
out.flush();
socket.shutdownInput(); // since you only send you may not need to call this
socket.shutdownOutput(); // with this you ensure that the data you "buffered" is sent
socket.close();
Generally if you want a graceful close, you should do it like this in all cases even for the server, so what you did is usually okay if there is an error and you just close the connection since you cant recover from an error.
i'm making a program/game that will update automatically. i have the update part down, but not the checking of the version. i would have thought that it'd be pretty easy. heres what i've done. i wrote an updater for the game, and i wrote a server. the server starts a thread every time a client/updater connects. the thread handles everything. the game updater reads a file called version.txt and that provides the version number (default 0.0.1) and sends it to the server. the server does recieve the version, and will System.out.println(); if the version matches, and if i change the version, it changes the output. so that part works. but that is as far as it goes. the second part of the process is that the server then sends just a text file called NPS Game.txt (it sends anything, but txt was easy to test with) and the client replaces the old version of this file with the new one that just sent. the problem is that i keep getting an error that says the Socket is closed. i've tried using socket.setKeepAlive(true); but that didnt change anything (i put that on both the client and the server). here is the code:
server:
package main;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class Server {
static ServerSocket serverSocket = null;
static Socket clientSocket = null;
static boolean listening = true;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(6987);
} catch (IOException e) {
ServerThread.showmsg("Could not use port: 6987");
System.exit(-1);
}
ServerThread.showmsg("server- initialized");
ServerThread.showmsg("server- waiting...");
while (listening)
new ServerThread(serverSocket.accept()).start();
}
}
server thread:
package main;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import javax.swing.JOptionPane;
public class ServerThread extends Thread {
Socket socket;
ObjectInputStream in;
ObjectOutputStream out;
String version = "0.0.1";
public ServerThread(Socket socket) {
super("Server Thread");
this.socket = socket;
}
public void run() {
showmsg("server- Accepted connection : " + socket);
getVersion();
sendFile();
}
public void getVersion() {
try {
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
try {
String s = (String) ois.readObject();
if (s.equals(version)) {
System.out.println("server- matched version :)");
} else {
System.out.println("server- didnt match version :(");
System.exit(0);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFile() {
// sendfile
File myFile = new File("C:\\Programming\\NPS\\Files\\bin\\NPS Game.txt");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis;
try {
fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
showmsg("server- Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
socket.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void showmsg(String s) {
JOptionPane.showMessageDialog(null, s);
}
}
and the client/updater:
package main;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import org.omg.CORBA.portable.InputStream;
public class Connections {
String IP, port;
String message = "";
Socket socket;
public Connections(boolean server, boolean updating, String IP, String port) {
this.IP = IP;
this.port = port;
try {
socket = new Socket(IP, Integer.parseInt(port));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!server) {
if (updating) {
try {
sendVersion();
updating();
} catch (IOException e) {
e.printStackTrace();
}
} else {
client();
}
}
if (server) {
}
}
public void sendVersion() throws IOException {
FileReader fileReader = new FileReader(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\version.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String stringRead = bufferedReader.readLine();
bufferedReader.close();
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject(stringRead);
oos.flush();
oos.close();
}
public void updating() throws IOException {
int filesize = 6022386; // filesize temporary hardcoded
int bytesRead;
int current = 0;
showmsg("client- connected");
// receive file
byte[] byteArray = new byte[filesize];
java.io.InputStream inStream = socket.getInputStream();
FileOutputStream fileOutStream = new FileOutputStream(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\NPS Game.txt");
BufferedOutputStream buffOutStream = new BufferedOutputStream(
fileOutStream);
bytesRead = inStream.read(byteArray, 0, byteArray.length);
current = bytesRead;
do {
bytesRead = inStream.read(byteArray, current,
(byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
buffOutStream.write(byteArray, 0, current);
buffOutStream.flush();
buffOutStream.close();
inStream.close();
socket.close();
}
public static void showmsg(String s) {
JOptionPane.showMessageDialog(null, s);
}
}
i dont know what's wrong with it, but it is really frusturating. if anyone can help, it would be appreciated. some things ive done: google all kinds of questions, tried implementing socket.setKeepAlive(true);. also, i thought it might be of note, in the server thread, right above the line BufferedInputStream bis = new BufferedInputStream(fis);, i put System.out.println(socket.isClosed); and it returned true. thats all i have. thanks in advance!
I think that closing one of both streams, closes the socket. So try to remove the ois.close() call out of your getVersion() method at the server side. Also get rid of the oos.close() call in your sendVersion() method at the client side.
When you construct an ObjectOutputStream or ObjectInputStream and you are done with it, you shouldn't close that stream, because it will close the underlying stream, which is in your case the socket.