I am developing server-client side java program, where I have sliced an jpg image using getSubimage() and saved into int image[][][]
The class below initialises connection with the server and receives an array, however compiler states that readObject() is undifined. Any suggestions how to fix this problem?
Thanks!
public void con() throws IOException {
int port = 7676;
ObjectInputStream inputStream = null;
Socket socket = null;
// try to establish the connection to the server
try {
socket = new Socket(hostName, port);
InputStreamReader is = new InputStreamReader(socket.getInputStream());
int pixels[][][] = new int[20][20][400];
pixels = (int[][][])is.readObject();
}
it must be of type ObjectInputStream, so you should write something like this:
pixels = (int[][][])inputStream.readObject();
where inputStream is type of ObjectInputStream.
Related
I am working on a client server java application, using serialization and deserialization. At first I simply want to send a serialized packet to the server that deserialize it and print it on the screen.
Here is mi Client:
public class Client {
public static void main(String[] args) throws IOException {
int portUDP = Integer.parseInt("6004");
InetAddress host = InetAddress.getByName("127.0.0.1");
DatagramSocket UDPsock = new DatagramSocket();
ByteArrayOutputStream oSt = new ByteArrayOutputStream();
ObjectOutputStream ooSt = new ObjectOutputStream(oSt);
packet pck = new packet(2,1,3,"try");
ooSt.writeObject(pck);
ooSt.flush();
byte[] sendBuf = new byte[30];
sendBuf = oSt.toByteArray();
DatagramPacket payload = new DatagramPacket(sendBuf, sendBuf.length, host, portUDP);
UDPsock.send(payload);
UDPsock.close();
}
}
And here is my Server:
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int portUDP = 6004;
DatagramSocket UDPsock = new DatagramSocket(portUDP);
byte[] payload = new byte[30];
DatagramPacket inUDP = new DatagramPacket(payload, payload.length);
UDPsock.receive(inUDP);
ByteArrayInputStream oSt = new ByteArrayInputStream(inUDP.getData());
ObjectInputStream ooSt = new ObjectInputStream(oSt);
packet pck = (packet)ooSt.readObject();
pck.printContents();
UDPsock.close();
}
}
I think that my problem is in the deserialization but I am not able to spot it. Please help me
This are my errors:
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2353)
at java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(ObjectInputStream.java:3092)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2892)
at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:1075)
at java.io.ObjectStreamClass.readNonProxy(ObjectStreamClass.java:717)
at java.io.ObjectInputStream.readClassDescriptor(ObjectInputStream.java:833)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1609)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1521)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1781)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at Server.main(Server.java:23)
byte[] payload = new byte[30];
The problem is here. Serialized streams are far bigger than this. Try 576.
And keep a watch on the size of the outgoing byte array as well. If this gets over 576 you will run into IP fragmentation, which will start to cause datagram loss, and you will eventually run into the path MTU which is generally only 1250-1500 bytes. So you can't serialize large objects.
Also:
ByteArrayInputStream oSt = new ByteArrayInputStream(inUDP.getData());
should be:
ByteArrayInputStream oSt = new ByteArrayInputStream(inUDP.getData(), inUDP.getOffset(), inUDP.getLength());
I want to send an object(array) from a client to a server. I use the ObjectInputStream and the ObjectOutputStream. However, this invokes an error, that these methods are not defined in serverSocket class.
How do I resolve the situation ??`
public int[] readResponse() throws IOException, ClassNotFoundException{
int[] x = new int[5];
ObjectOutputStream cO = new ObjectOutputStream(serverSocket.getOutputStream()); //here is the error
ObjectInputStream cI = new ObjectInputStream(serverSocket.getInputStream()); // here is the error
cO.writeObject(x);
x = (int[]) cI.readObject();
for (int i = 0; i < 5; i++){
System.out.println(x[i]);
}
return x;
}
A java.net.ServerSocket is not meant to be used for actual input and output; it is a socket for listening on the server to incoming connection requests which are accepted, resulting in a java.net.Socket which is then the one for reading and writing.
Socket socket = serverSocket.accept();
ObjectInputStream cI =
new ObjectInputStream(socket.getInputStream());
On the client side, a java.net.Socket is created by calling the constructor and connected, via an address, to the client.
Socket socket = new Socket( address, port );
ObjectOutputStream cO =
new ObjectOutputStream(socket.getOutputStream());
I set up a client and server sockets. When I use classes ObjectOutputStream and ObjectInputStream and the method readObject/writeObject everything works fine.
It simulates communication with a robot that I know for sure interprets correctly only method
DataOutputStream.writeBytes.
So I set up the new architecture for simulation since the robot is not available for testing on a daily basis.
In the following code where ObjectOutputStream/ObjectInputStream readObject/writeObject were replaced with DataInputStream/DataOutputStream writeBytes and IOutils.toByteArray.
The server socket correctly receives the message but when it tries to write back a response I get a broken pipe as if the connection was closed somewhere.
Notice that I never close sockets or streams because the robot can answer even after 30 seconds.
Any help to make DataOutputStream.writeBytes work would be appreciated.
Here's the non-working code:
Client:
Socket serverSocket = new Socket("server", 9899);
DataOutputStream outputStream = new DataOutputStream(serverSocket.getOutputStream());
//ObjectOutputStream outputStream = new ObjectOutputStream(serverSocket.getOutputStream());
//outputStream.writeObject("\n" + "message" + "\r");
outputStream.writeBytes("\n" + "message" + "\r");
outputStream.flush();
DataInputStream inputStream = new DataInputStream(serverSocket.getInputStream());
//ObjectInputStream inputStream = new ObjectInputStream(serverSocket.getInputStream());
byte [] bytes = IOUtils.toByteArray(inputStream);
String serverResponse = new String(bytes,"UTF-8");
// String serverResponse = (String)inputStream.readObject();
Server:
ServerSocket serverSocket = new ServerSocket(9899);
while (true) {
Socket socket = serverSocket.accept();
//ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
byte [] bytes = IOUtils.toByteArray(inputStream);
String message = new String(bytes,"UTF-8");
//String message = (String) inputStream.readObject();
Thread.sleep(15000);
//ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
//outputStream.writeObject("server response");
outputStream.writeBytes("server response"); //EXCEPTION THROWN HERE FOR BROKEN PIPE
outputStream.flush();
}
Thanks for your time
IOUtils.toString(InputStream) must read the stream until its end, which would imply that the peer has disconnected. So you can't write to it.
If you're exchanging Strings with data streams you should use writeUTF() and readUTF().
Or read and write lines, with a BufferedReader/Writer.
I'm trying to send an image using a Java server to my Android device but it doesn't work and I don't know why.
The code for the server is:
public class Main {
public static void main(String argv[]) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(6789);
Image image = null;
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
ObjectOutputStream outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());
File f = new File("/resources/image.png");
image = ImageIO.read(f);
outToClient.writeObject( new ImageIcon(""+image) );
}
}
}
I think the problem is in the server because the Android app works with another server
client:
BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
DataInputStream in;
BufferedInputStream buf;
DataInputStream mod ;
Socket sc = new Socket(myIP,48000);
DataInputStream infromServer = new DataInputStream(sc.getInputStream());
mod = infromServer;
Bitmap mPhotoPicture = BitmapFactory.decodeStream(modifiedSentence);
imagen.setImageBitmap((mPhotoPicture));
The other server is probably sending the raw image data (not an ImageIcon serialized object). It looks like BitmapFactory expects the image's raw bytes. Try writing the raw bytes out to your socket:
FileInputStream fis = null;
int size = (int)f.length();
byte[] bytes = new byte[size];
fis = new FileInputStream( f );
int read = fis.read( bytes );
connectionSocket.getOutputStream().write( bytes );
connectionSocket.getOutputStream().flush();
Obviously, you'll need to add some error detection and handling to make this robust.
Hello there im trying to send files using client-server classes in java. For some reason when the method that sends the file is called the socket closes. here is the code :
FileInputStream fIn = new FileInputStream(file);
out = new BufferedOutputStream(clientSocket.getOutputStream());
byte fileContent[] = new byte[(int) file.length()];
fIn.read(fileContent);
for (byte b : fileContent) {
out.write(b);
}
and the code from the client :
FileOutputStream fIn = new FileOutputStream("testing");
BufferedInputStream inAout = new BufferedInputStream(clientSocket.getInputStream());
byte fileContent[] = new byte[1000000];
inAout.read(fileContent);
fIn.write(fileContent);
and the error message i get : SEVERE: null
java.net.SocketException: Socket closed
Im not really experienced with this so if any can help it would be great.
The InputStream.read(byte[]) method returns an int for the number of bytes it actually read. It's not guaranteed to read as many bytes as you requested from the byte array. It'll often return the size of the underlying buffer and you'll have to call it many times.
You can use this to be more efficient by streaming the bytes from the socket to the file instead of buffering the whole byte array in memory. Likewise on the server side you can do the same thing to save memory and be faster than writing a byte at a time.
Here's a working example of a server and client in one that connects to itself to transfer a file:
public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("send.jpg");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}
static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("recv.jpg");
copy(in, out);
out.close();
in.close();
}
static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
client();
}
}
The reason is pretty simple: The call inAout.read(fileContent) will return after about 4KB of data has been transmitted. That's the input buffer size. So instead of a single huge read, you need a loop and many reads and write as many bytes to fIn as you got from the socket.
Also don't forget to flush the output on the server side (closing will flush it) or some data will be lost.
SEVERE: null java.net.SocketException: Socket closed
That means you've closed the socket yourself and then called another operation that needs it open. For example, closing the socket or its input stream or output stream closes the other stream and the socket. Somewhere or other you are doing that.