Sending graphics object from server to client - java

I'm writing a program where the server draws a shape in its app and the client can see that shape in its own app. I thought about converting the object to a byte array but it didn't do anything.
The server code
private void sendShape(Graphics drawedShape) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(drawedShape);
oos.flush();
byte[] yourBytes = bos.toByteArray();
/*oos.writeObject(drawedShape);
oos.flush();
dispMessage("\n Teacher:" + "Shape sent!");*/
} catch (IOException e) {
jta.append("\nError");
}
}
The client code
private void processConn() throws IOException {
send("Successful");
setButtonEnabled(true);
String msg = "";
Graphics object;
ByteArrayInputStream bis = null;
do {
try
{
Object incomingObject = ois.readObject();
if(incomingObject.getClass().toString().contains("Graphics"))
{
try {
ois = new ObjectInputStream(bis);
Object o = ois.readObject();
/*object = (Graphics) ois.readObject();
dispMessage("\n" + object);*/
}finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException ex) {
}
}
}

Related

Strange EOFexception while do readObject() in deserialization

I am trying to process an object on the server with UDP. I serialize it, send it to the server. On the server, I deserialize, modify, then serialize back to send back to the client. On the client I get it, and when I try to readObject () I get an EOF exception. Please help, what could be the problem? I didn't find the answer anywhere.
This is client:
public class Client {
public static void main(String[] args) {
Help help = new Help("WTF");
try {
byte[] objByteArray = serialize(help);
DatagramSocket ds = new DatagramSocket();
InetAddress host = InetAddress.getLocalHost();
int port = 6789;
int objLength = objByteArray.length;
DatagramPacket dp = new DatagramPacket(objByteArray, objLength, host, port);
ds.send(dp);
dp = new DatagramPacket(objByteArray, objLength);
ds.receive(dp);
byte[] new_arr = objByteArray;
Help deserializedObj = (Help) deserialize(objByteArray);
System.out.println(deserializedObj.getData());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SocketException e) {
throw new RuntimeException(e);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] serialize(Object obj) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)){
oos.writeObject(obj);
byte[] objByteArray = baos.toByteArray();
return objByteArray;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Object deserialize(byte[] arr) throws IOException, ClassNotFoundException {
Object result = null;
try (ByteArrayInputStream bais = new ByteArrayInputStream(arr);
ObjectInputStream ois = new ObjectInputStream(bais)){
result = ois.readObject();
}
catch (IOException e){
}
return result;
}
}
And this is Server:
public class Server {
public static void main(String[] args) throws IOException {
String filepath = System.getProperty("user.dir") + "\\src\\Server\\Data\\Collection.json";
CollectionManager.setFilePath(filepath);
byte[] arr = new byte[100000];
DatagramSocket ds = new DatagramSocket(6789);
DatagramPacket dp = new DatagramPacket(arr, arr.length);
ds.receive(dp);
try {
Help deserializedObj = (Help) deserialize(arr);
deserializedObj.setData("Server finished work!");
System.out.println("Done!");
byte[] serializedObj = serialize(deserializedObj);
InetAddress host = dp.getAddress();
int port = dp.getPort();
dp = new DatagramPacket(serializedObj, serializedObj.length, host, port);
ds.send(dp);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static byte[] serialize(Object obj) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)){
oos.writeObject(obj);
byte[] objByteArray = baos.toByteArray();
return objByteArray;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Object deserialize(byte[] arr) throws IOException, ClassNotFoundException {
Object result = null;
try (ByteArrayInputStream bais = new ByteArrayInputStream(arr);
ObjectInputStream ois = new ObjectInputStream(bais)){
result = ois.readObject();
}
catch (IOException e){
}
return result;
}
}
And also the classes:
public class Help extends Command implements Serializable {
public Help(String name){
super.setName(name);
}
private String data;
public void setData(String s){
data = s;
}
public String getData(){
return data;
}
#Override
public void execute() {
}
}
The problem was that the packet sent from the server is larger than the original one, therefore, on the client, we must receive data into the buffer with a margin, and from there try to read the data.
This is an edited Client code:
byte[] buffer = new byte[1024];
dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);

How to fix java EOFException using ObjectInbputStreem in java network

I want to send some objects using network. My network I made it using DatagramSocket, DatagramPacket, ByteArrayInputStream, ObjectInputStream, ByteArrayOutputStream and ObjectOutputStream.
When I was trying to send an object using network I got java.io.EOFException and when I handled this exception using try and catch I lost my object.
Server Side
public class GameServer extends Thread {
private DatagramSocket socket;
private DatagramPacket packet;
private byte[] data;
private ByteArrayInputStream bais;
private ObjectInputStream ois;
private ByteArrayOutputStream baos;
private ObjectOutputStream oos;
private Game game;
public GameServer() {
try {
this.socket = new DatagramSocket(1331);
}
catch (SocketException e) {
e.printStackTrace();
}
start();
}
#Override
public void run() {
while (true) {
data = new byte[6400];
packet = new DatagramPacket(data, data.length);
Object object = receive();
if (object instanceof String) {
String message = (String) object;
System.out.println("CLIENT [ " + packet.getAddress().getHostAddress() + " : " + packet.getPort() + " ] >> " + message.trim());
if (message.equalsIgnoreCase("start")) {
game = new Game("Tankies", 1200, 700);
sendObject(game);
}
}
else if (object instanceof State) {
System.out.println("got state");
}
else if (object instanceof Player)
System.out.println("hi player");
}
}
private Object receive() {
bais = new ByteArrayInputStream(data);
try {
socket.receive(packet);
ois = new ObjectInputStream(new BufferedInputStream(bais));
return ois.readObject();
} catch (EOFException e) {
System.out.println("SERVER Got EOFException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private void sendData(byte[] data, InetAddress ipAddress, int port) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
try {
this.socket.send(packet);
}
catch (IOException e) {
e.printStackTrace();
}
}
private void sendObject(Object object) {
baos = new ByteArrayOutputStream(6400);
oos = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
}
catch (IOException e) {
e.printStackTrace();
}
sendData(baos.toByteArray(), packet.getAddress(), packet.getPort());
}
}
Client Side
public class GameClient extends Thread implements Serializable {
private InetAddress ipAddress;
private transient DatagramSocket socket;
private transient DatagramPacket packet;
private byte[] data;
private transient ByteArrayInputStream bais;
private transient ObjectInputStream ois;
private transient ByteArrayOutputStream baos;
private transient ObjectOutputStream oos;
private Game game;
public GameClient(String ipAddress) {
try {
this.socket = new DatagramSocket();
}
catch (SocketException e) {
e.printStackTrace();
}
try {
this.ipAddress = Inet4Address.getByName(ipAddress);
}
catch (UnknownHostException e) {
e.printStackTrace();
}
start();
}
#Override
public void run() {
while (true) {
data = new byte[6400];
packet = new DatagramPacket(data, data.length);
Object object = receive();
if (object instanceof String) {
System.out.println("SERVER >> " + object);
}
else if (object instanceof Game) {
this.game = (Game) object;
this.game.setClient(this);
this.game.start();
}
}
}
private Object receive() {
bais = new ByteArrayInputStream(data);
try {
socket.receive(packet);
ois = new ObjectInputStream(new BufferedInputStream(bais));
return ois.readObject();
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private void sendData(byte[] data) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 1331);
try {
this.socket.send(packet);
}
catch (IOException e) {
e.printStackTrace();
}
}
public void sendObject(Object object) {
baos = new ByteArrayOutputStream(6400);
oos = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
}
catch (IOException e) {
e.printStackTrace();
}
sendData(baos.toByteArray());
}
}
Code to send the object to server
public class MultiplayerState extends State{
private World world;
private Tank myTank, playerTank;
public MultiplayerState(Handler handler) {
super(handler);
}
#Override
public void startState() {
world = new World(handler,"res/worlds/world1.txt");
handler.setWorld(world);
myTank = new Tank(handler, world.getSpawnX(), world.getSpawnY());
handler.getGame().getRender().addObject(world);
handler.getGame().getRender().addObject(myTank);
world.start();
myTank.start();
handler.getGame().getClient().sendObject(handler.getGame().getPlayer());
}
}
handler.getGame().getClient().sendObject(handler.getGame().getPlayer());
This line to send player to server .. some explanation about code .. this is a game using multithreading in java and i want to create simple network to make two different laptops playing this game online because of that i made this network. I created class Handler this is a class to manage all the game, using object instance of Handler class I can get anything in the game and I want to get object instance of Player class to send it to server because I want to do something to make the game online.
I solved this exception by made GameClient object in Game class transient because I don't want to serialize it. What I want is to use this object to send something to server from Game object internally.

How to clone an Object by copy ByteArrayOutputStream into ByteArray, then call it by ByteArrayInputStream?

I try to clone an Object by 1) shoving it into a ByteArrayOutputStream 2) assigning the stream to a byte array 3) reading the byte array by ByteArrayInputStream. However, this won't work as I can not assign the OutputStream to the byte array, the line will just not execute.
Apporoach is based Java Serializable Object to Byte Array
public Bank clone() {
Bank objektKopie = null;
byte[] byteKopie = null;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = null;
try {
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(this);
oo.flush() ;
byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
bo.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
ObjectInputStream oi = null;
try {
oi = new ObjectInputStream(bi);
objektKopie = (Bank) oi.readObject();
} catch (Exception e) { System.out.println(e.getMessage()); }
return objektKopie;
}
Your code is throwing "NotSerializable" exception, your class Bank NEEDS to implement Serializable
if dependencies are okay, GSON can do this fairly easily

Read and Write text file from my own class in Android Studio

I have been trying to create a class called TextFileReaderWriter I want to use the getters and setters to read and write to a text file in such a way that I can call the class and the method from anywhere in the program by simply using setfileContents(somestring) and somestring = getfileContents() something like this
example:
TextFileReaderWriter trw = new TextFileReaderWriter();
trw.setfileContents(somestring); //this would write 'somestring' to the text file.
String somestring = trw.getfileContents(); //this would return 'somestring' from the text file.
Here's what I have so far but it writes nothing to the file:
public class TextFileReaderWriter extends Activity{
String fileContents;
Context context;
String TAG = "MYTAG";
public TextFileReaderWriter(String fileContents, Context context) {
this.fileContents = fileContents;
this.context = context;
}
public String getFileContents() {
return fileContents;
}
public void setFileContents(String fileContents) {
this.fileContents = fileContents;
FileOutputStream fos = null;
try {
fos = context.openFileOutput("UserInputStore", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(fileContents);
Log.d(TAG, fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You don't need the OutputStreamWriter--FileOutputStreamwill do the trick just fine.
//what you had before
FileOutputStream fos = null;
try {
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//use just the file output stream to write the data
//data here is a String
if (fos != null) {
try {
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Method to save data on disk :
protected static void saveDataOnDisk(String data) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream);
objectOutput.writeObject(data);
byte[] buffer = byteArrayOutputStream.toByteArray();
File loginDataFile = (new File(filePath)); // file path where you want to write your data
loginDataFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile);
fileOutputStream.write(buffer);
fileOutputStream.close();
objectOutput.flush();
objectOutput.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
Log.i(“SAVE”, ”———————-DONE SAVING”);
} catch(IOException ioe) {
Log.i(“SAVE”, “———serializeObject|”+ioe);
}
}
Method to fetch data from disk:
private static Object getDataFromDisk() {
try {
FileInputStream fileInputeStream = new FileInputStream(FilePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream);
Object data = (Object) objectInputStream.readObject();
objectInputStream.close();
fileInputeStream.close();
return dataModel;
} catch (Exception error) {
Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error);
}
return null;
}

Why is this exception thrown and how to recover from it?

I am creating a remote-desktop screenshot application. I have two methods on the server 1) To read the Image from client 2) to read the list of task running on the client). But everytime I try to read the client's input stream an EOF excetion is thrown. The stakctrace of the exception is
java.io.EOFException at
java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2323)
at
java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2792)
at
java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:799)
at java.io.ObjectInputStream.(ObjectInputStream.java:299) at
remoteserverclient.original.ScreenServer$ServerThread.run(ScreenServer.java:254)
Here is the code on the server where the exception is thrown
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
Object obj = in.readObject();
if (obj instanceof Rectangle) {
CaptureScreen(obj, in);
} else if (obj instanceof String) {
CaptureList(in);
}
Here is the complete code for the client
public class ScreenClient {
static Socket server;
public static void main(String[] args) throws Exception {
try {
while (true) {
server = new Socket("localhost", 5494);
BufferedReader bf = new BufferedReader(new InputStreamReader(server.getInputStream()));
String s;
s = bf.readLine();
System.out.println(s);
if (s.contains("execute")) {
new ClientMessageThread().start();
}
if (s.contains("getProcessList")) {
new ClientFetchProcessThread().start();
}
}
} catch (Exception e) {
System.err.println("Disconnected From server ->" + e.getMessage());
}
}
public static class ClientMessageThread extends Thread {
Socket server;
public ClientMessageThread() {
try {
server=new Socket("localhost",5494);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void run() {
try {
BufferedImage screen;
Robot robot = new Robot();
Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
screen = robot.createScreenCapture(size);
int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];
screen.getRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());
OutputStream baseOut = server.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baseOut);
out.writeObject(size);
for (int x = 0; x < rgbData.length; x++) {
out.writeInt(rgbData[x]);
}
out.flush();
server.close();
//added new
} catch (Exception e) {
System.err.println("Disconnected From server ->" + e.getMessage());
}
}
}
public static class ClientFetchProcessThread extends Thread {
Socket server;
public ClientFetchProcessThread() {
try {
server=new Socket("localhost",5494);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
try {
PrintWriter ps;
System.out.println("\n\n********");
StringBuilder builder = new StringBuilder("");
String query = "tasklist";
Runtime runtime = Runtime.getRuntime();
InputStream input = runtime.exec(query).getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
String line = "";
ps = new PrintWriter(server.getOutputStream(), true);
while ((line = commandResult.readLine()) != null) {
builder.append(line + "\n");
//byte[] responseClient=s.getBytes();
ps.write(builder.toString());
System.out.println(builder.toString());
}
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You're both printing and writing objects to port 5494 from the client. The server only reads objects.
Sort it out.
The exception being thrown is EOFException (End of file exception).
ObjectInputStream throws EOFException when it reaches the end of the input. That's standard behaviour. Are you catching all exceptions thrown by in.readObject()?
Documentation:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html

Categories