Serialize/Deserialize Java object through network and byte array - java

I have this code from DZone(http://www.dzone.com/links/r/java_custom_serialization_example.html) that serialize/deserialize Java object from/to file.
final class Hello implements Serializable
{
int x = 10;
int y = 20;
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
public class SerializedComTest {
#AfterClass
public static void tearDownAfterClass() throws Exception {
}
#Test
public void testFile() throws IOException, ClassNotFoundException {
Hello h = new Hello();
FileOutputStream bs = new FileOutputStream("hello.txt"); // ("testfile");
ObjectOutputStream out = new ObjectOutputStream(bs);
out.writeObject(h);
out.flush();
out.close();
Hello h2;
FileInputStream fis = new FileInputStream("hello.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
h2 = (Hello) ois.readObject();
assertTrue(10 == h2.getX());
assertTrue(20 == h2.getY());
}
}
How can I transfer serialized object using Java socket? And also how can I store the serialized/deserialized object to/from a byte array.

This is the code for serialization to/from byte array. I got hints from - Java Serializable Object to Byte Array
#Test
public void testByteArray() throws IOException, ClassNotFoundException, InterruptedException {
Hello h = new Hello();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(h);
byte b[] = bos.toByteArray();
out.close();
bos.close();
Hello h2;
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
h2 = (Hello) in.readObject();
assertTrue(10 == h2.getX());
assertTrue(20 == h2.getY());
}

How can I transfer serialized object using Java socket?
Wrap its output stream in an ObjectOutputStream.
And also how can I store the serialized/deserialized object to/from a string.
You don't. Serialized objects are binary, and should be stored in byte arrays. A deserialized object is the object itself, not a string.
You don't need those readObject() and writeObject() methods. They don't do anything that wouldn't happen by default.

Like you wrapped your filestream with the objectstream class, you do the same with sockets. You should not "store" a serialized object to a string.

This is the code that works, and I got the hint from http://cyberasylum.janithw.com/object-serialization-over-networks-in-java/.
#Test(timeout = 2000)
public void testStream() throws IOException, ClassNotFoundException, InterruptedException {
PingerThread pinger = new PingerThread(9092);
pinger.start();
String serverAddress = "localhost";
Socket s;
PrintWriter output;
BufferedReader input;
try {
// Client
s = new Socket(serverAddress, 9092);
}
catch (IOException e)
{
// when error, try again
Thread.sleep(500);
s = new Socket(serverAddress, 9092);
}
// send the object over the network
Hello h = new Hello();
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(h);
out.flush();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
System.out.println("2");
Hello h2;
h2 = (Hello) in.readObject();
assertTrue(10 == h2.getX());
assertTrue(20 == h2.getY());
}
private class PingerThread extends Thread {
public int portNumber;
public PingerThread(int portNumber) {
super();
this.portNumber = portNumber;
}
#Override
public void run() {
try {
ServerSocket listener = new ServerSocket(this.portNumber);
Socket socket = listener.accept();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
Hello h;
while((h = (Hello) in.readObject()) != null) {
System.out.println("1");
//h = (Hello) in.readObject();
System.out.println(h.getX());
System.out.println(h.getY());
out.writeObject(h);
out.flush();
}
System.out.println("OUT");
socket.close();
listener.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Related

Why can't I read an object from a binary file using ObjectInputStream wrapped with a FIleInputStream?

public class JavaApplication {
public static void main(String[] args) throws IOException{
URL u = new URL("https://www.javatpoint.com/java-string-valueof");
byte[]bytes= u.openStream().readAllBytes();
ObjectOutputStream output= new ObjectOutputStream(
new FileOutputStream("binary.dat"));
output.write(bytes);
output.close();
//Scanning the URL works just not the try and catch block
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream
("binary.dat"));
byte[]byte1= (byte[])input.readObject();
String any;
for(int i=0; i<byte1.length; i++){
any=String.valueOf(byte1[i]);
System.out.println(any);
}
input.close();
}
catch(Exception e){
System.out.println(e);}
}
}
I used a new byte array to read the object from file, use String.valueOf() to obtain the String value of the byte, then a for-loop to iterate the String. What am I doing wrong?
As the first commenter said, your main problem was not using writeObject. The only other problem is the way you turn the bytes into text. Your code will result in the 'ascii' code of the character being printed instead of the character itself. In fact you can simplify the output code as follows:
import java.io.*;
import java.net.*;
public class JavaApplication {
public static void main(String[] args) throws IOException {
URL u = new URL("https://www.javatpoint.com/java-string-valueof");
byte[] bytes = u.openStream().readAllBytes();
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("binary.dat"));
output.writeObject(bytes);
output.close();
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream("binary.dat"));
byte[] byte1 = (byte[]) input.readObject();
System.out.println(new String(byte1));
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To solve your problem, I prefer you :
Add implementation of URLConnection for avoidance from Http Status 403 / Forbidden. Reference
use ByteArrayOutputStream to write the byte and save it into file using ObjectOutputStream
if you read with readObject() you must write with writeObject()
public class JavaApplication {
public static void main(String[] args) throws IOException, ClassNotFoundException {
URL u = new URL("https://www.javatpoint.com/java-string-valueof");
URLConnection uc = u.openConnection();
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = uc.getInputStream();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ((n = is.read(byteChunk)) > 0) {
baos.write(byteChunk, 0, n);
}
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s: %s", u.toExternalForm(), e.getMessage());
} finally {
if (is != null) {
is.close();
}
}
byte[] bytes = baos.toByteArray();
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("binary.dat"));
output.writeObject(bytes);
output.close();
//Scanning the URL works just not the try and catch block
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream("binary.dat"));
byte[] byte1 = (byte[]) input.readObject();
String any;
for (int i = 0; i < byte1.length; i++) {
any = String.valueOf(byte1[i]);
System.out.println(any);
}
input.close();
} catch (IOException e) {
System.out.println(e);
}
}
}

ObjectInputStream header problems [duplicate]

I am trying to convert a ArrayList object to a byte string so it can be sent via sockets. When I run this code it converts to a string properly but when I try to convert it back I get the exception "java.io.StreamCorruptedException: invalid stream header: EFBFBDEF". Other answers I looked at on here didn't really help as I am using the matching ObjectOutputStream and ObjectInputStream. Sorry if there is a simple fix as I am new to working with stream objects.
try {
ArrayList<String> text = new ArrayList<>();
text.add("Hello World!");
String byteString = Utils.StringUtils.convertToByteString(text);
ArrayList<String> convertedSet = (ArrayList<String>) Utils.StringUtils.convertFromByteString(byteString);
VCS.getServiceManager().addConsoleLog(convertedSet.get(0));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
public static String convertToByteString(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(object);
final byte[] byteArray = bos.toByteArray();
return new String(byteArray);
}
}
public static Object convertFromByteString(String byteString) throws IOException, ClassNotFoundException {
final byte[] bytes = byteString.getBytes();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
I figured it out. I had to use Base64 encoding. The conversion methods have to be changed to the following:
public static String convertToByteString(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(object);
final byte[] byteArray = bos.toByteArray();
return Base64.getEncoder().encodeToString(byteArray);
}
}
public static Object convertFromByteString(String byteString) throws IOException, ClassNotFoundException {
final byte[] bytes = Base64.getDecoder().decode(byteString);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
String is not a container for binary data. You need to pass around the original byte array, or hex- or base64-encode it.
Better still, serialize directly to the socket and get rid of this altogether.

convert byte stream to string from socket in server side java

I serialized an object to bytes and send to the server side.
in the server side i got the byte stream but i want to print the object/string i got from the server in order to verify i got it well
server side:
CarServerSocket = new ServerSocket(4441);
System.out.println("Server is ready and waiting for connection from client..\n");
try {
while (true) {
carSocket = CarServerSocket.accept();
System.out.println("Server Connected");
final DataInputStream bytesIR = new DataInputStream(carSocket.getInputStream());
bytesIRLength = bytesIR.readInt();
while (bytesIRLength > 0) {
byte[] messageIn = new byte[bytesIRLength];
bytesIR.readFully(messageIn,0,messageIn.length);
bytesIR.readUTF();
}
}
}catch(EOFException e ){
System.out.println("\ngot all objects from client.\ndisconnecting server...");
CarServerSocket.close();
carSocket.close();
}
}
Cliend side - serialization
objectOut.writeObject(CarList[i]); // converting object to bytes.
objectOut.flush();
objectInBytes = byteOut.toByteArray();
System.out.println("Sending car object #"+i);
dOut.writeInt(objectInBytes.length); // getting object bytes size.
dOut.write(objectInBytes); // sending object in bytes.
I tired to use: toString(), readUTF()... but no luck.
can anyone please advise how i solve it?
Thank you.
You can try to read data from your InputStream with some kind of InputStreamReader, something like this :
CarServerSocket = new ServerSocket(4441);
System.out.println("Server is ready and waiting for connection from client..\n");
try {
while (true) {
carSocket = CarServerSocket.accept();
System.out.println("Server Connected");
StringBuilder yourData = new StringBuilder();
new BufferedReader(new InputStreamReader(carSocket.getInputStream()))
.lines().forEach(stringBuilder::append);
System.out.println(yourData.toString());
}catch(EOFException e ){
System.out.println("\ngot all objects from client.\ndisconnecting server...");
CarServerSocket.close();
carSocket.close();
}
}
objectOut.writeObject(CarList[i]); // converting object to bytes.
objectOut.flush();
objectInBytes = byteOut.toByteArray();
System.out.println("Sending car object #"+i);
dOut.writeInt(objectInBytes.length); // getting object bytes size.
dOut.write(objectInBytes); // sending object in bytes.
All this is completely pointless. It just wastes time and space. Just use ObjectOutputStream.writeObject() directly to the socket at the sender, and ObjectInputStream.readObject() directly from the socket at the receiver.
You need to use ObjectInputStream to deserialize objects. Ok, so your object is entirely contained in a datagram that you've already received. You just need to turn the data buffer into an ObjectInputStream. Coding from the hip, this would be something like ...
try( ByteArrayInputStream bais = new ByteArrayInputStream(messageIn);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
}
Edit: Here is some complete code showing this working.
public class ByteStream {
public static void main(String[] args) throws IOException {
Server server = new Server(4441);
new Thread(server).start();
Client client = new Client(4441);
new Thread(client).start();
}
}
class Client implements Runnable {
private final Socket socket;
Client(int port) throws UnknownHostException, IOException {
socket = new Socket("localhost", port);
}
#Override
public void run() {
MyObject send = new MyObject();
send.x = 10;
send.msg = "X = ";
try {
try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(send);
oos.flush();
byte[] objectInBytes = baos.toByteArray();
int length = objectInBytes.length;
System.out.println("Client: sending 'objectInBytes' length = " + length);
dos.writeInt(length);
dos.write(objectInBytes);
} finally {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server implements Runnable {
private final ServerSocket serverSocket;
Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
#Override
public void run() {
try {
try (Socket socket = serverSocket.accept();
DataInputStream bytesIR = new DataInputStream(socket.getInputStream())) {
int length = bytesIR.readInt();
byte[] messageIn = new byte[length];
bytesIR.readFully(messageIn);
System.out.println("Server: got datagram length = " + length);
process(messageIn);
} finally {
serverSocket.close();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void process(byte[] messageIn) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(messageIn);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
System.out.println(o.getClass() + ": " + o);
}
}
}
class MyObject implements Serializable {
private static final long serialVersionUID = -1478875967217194114L;
double x;
String msg;
public String toString() { return msg + x; }
}
And the output:
Client: sending 'objectInBytes' length = 75
Server: got datagram length = 75
class MyObject: X = 10.0

How to send multiple images using socket programing in java and write on specific path on server side?

I want to send multiple images from client side to server side on different systems in wifi and in server side write this files on specific location.
Thanks in advance.
In Client.java file
public class Client {
public void send(String file_name){
try {
Socket socket = new Socket("IBM-PC", 3332);
File file = new File(file_name);
System.out.println(file_name);
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[Server.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
ois = null;
oos = null;
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Client c = new Client();
c.send("D://1.jpg"); // first image path
c.send("D://0.jpg"); // second image path
}
}
In Server.Java File
public class Server extends Thread {
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 500102;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte[] buffer = new byte[BUFFER_SIZE];
// 1. Read file name.
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream("D:\\temp\\"+o.toString()); // Edit it for specific path
System.out.println("D:\\temp\\"+o.toString());
} else {
throwException("Something is wrong");
}
// 2. Read file to the end.
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer) o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[]) o;
// 3. Write data to output file.
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println("File transfer success");
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}
First run server.java file and then run client.java file
I hope it'll help you...

how to keep a "Hello World" type server running

How do I keep the server "open" so that it can send and receive objects on a continuing basis without crashing? Basically, I would like to put an infinite loop around the readRecord method, so that it runs indefinitely.
server:
package net.bounceme.dur.driver;
import java.net.*;
import java.io.*;
import java.util.Properties;
import java.util.logging.Logger;
public class Server {
private static final Logger log = Logger.getLogger(Server.class.getName());
private final RecordQueue recordsQueue = new RecordQueue();
public static void main(String[] args) throws IOException {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
new Server().readRecord(portNumber);
}
public void readRecord(int portNumber) throws IOException {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket socket = serverSocket.accept();
ObjectOutputStream objectOutputStream = null;
MyRecord recordFromClient = null;
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
while (true) {
try {
recordFromClient = (MyRecord) objectInputStream.readObject();
} catch (ClassNotFoundException e) {
System.out.println(e);
}
objectOutputStream.writeObject(recordFromClient);
}
}
}
client:
package net.bounceme.dur.driver;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Client {
private List<MyRecord> iterate() {
MyRecord myRecord = null;
List<MyRecord> records = new ArrayList<>();
for (int i = 0; i < 9; i++) {
myRecord = new MyRecord(i, "foo");
records.add(myRecord);
}
return records;
}
public void simple(String server, int portNumber) throws IOException, ClassNotFoundException {
Socket s = new Socket(server, portNumber);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
List<MyRecord> records = iterate();
for (MyRecord record : records) {
oos.writeObject(record);
}
oos.flush();
Object received = ois.readObject();
System.out.println(received);
oos.close();
ois.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
String server = (props.getProperty("server"));
new Client().simple(server, portNumber);
}
}
server output:
thufir#dur:~$
thufir#dur:~$ java -jar NetBeansProjects/Server/dist/Server.jar
Exception in thread "main" java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1876)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1785)
at java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1285)
at java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1230)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1426)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1576)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:350)
at net.bounceme.dur.driver.Server.readRecord(Server.java:32)
at net.bounceme.dur.driver.Server.main(Server.java:16)
thufir#dur:~$
client output:
thufir#dur:~$
thufir#dur:~$ java -jar NetBeansProjects/Client/dist/Client.jar
value=0, id='foo
thufir#dur:~$
Okay what your problem is, your server was made to only read and handle one object at a time. So When you client tries to send all of those MyRecord objects, the server reads one, and then tries to send it back to you, the problem is, you are still trying to send the other MyRecord objects while the server is trying to send you the FIRST MyRecord object. Client/Server connections are like a game of tennis. One person must serve the ball to the other player, and the other must then hit the ball back. You cannot both hit a ball with neither of you recieving.
So in,
for (MyRecord record : records) {
oos.writeObject(record);
}
oos.flush();
Object received = ois.readObject();
System.out.println(received);
you should put the
oos.flush();
Object received = ois.readObject();
System.out.println(received);
inside of the for() loop, that way each MyRecord object is sent to the server, read by the server, sent back to the client by the server, and read by the client.
Final result:
for (MyRecord record : records) {
oos.writeObject(record);
oos.flush();
Object received = ois.readObject();
System.out.println(received);
}
See the changes(i edited some code to run on my machine, so make your changes appropriately)
import java.net.*;
import java.io.*;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.List;
class MyRecord implements java.io.Serializable
{
int x;
String y;
MyRecord(int a,String b)
{
x=a;
y=b;
}
}
class Server {
private static final Logger log = Logger.getLogger(Server.class.getName());
//private final RecordQueue recordsQueue = new RecordQueue();
public static void main(String[] args) throws IOException {
//Properties props = PropertiesReader.getProps();
//int portNumber = Integer.parseInt(props.getProperty("port"));
new Server().readRecord(2*1000);
}
public void readRecord(int portNumber) throws IOException {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket socket = serverSocket.accept();
ObjectOutputStream objectOutputStream = null;
MyRecord recordFromClient = null;
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
while (true) {
try {
recordFromClient = (MyRecord) objectInputStream.readObject();
if(recordFromClient.x==-1) {break;}
} catch (ClassNotFoundException e) {
System.out.println(e);
}
objectOutputStream.writeObject(recordFromClient);
objectOutputStream.flush();
}
}
}
class Client {
private List<MyRecord> iterate() {
MyRecord myRecord = null;
List<MyRecord> records = new ArrayList<>();
for (int i = 0; i < 9; i++) {
myRecord = new MyRecord(i, "foo");
records.add(myRecord);
}
return records;
}
public void simple(String server, int portNumber) throws IOException, ClassNotFoundException {
Socket s = new Socket(server, portNumber);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
List<MyRecord> records = iterate();
for (MyRecord record : records) {
oos.writeObject(record);
oos.flush();
Object received = ois.readObject();
System.out.println(received);
}
MyRecord record= new MyRecord(-1,"end");
oos.writeObject(record);
oos.flush();
oos.close();
ois.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException {
//Properties props = PropertiesReader.getProps();
//int portNumber = Integer.parseInt(props.getProperty("port"));
String server = "localhost";
new Client().simple(server, 2000);
}
}
This works to a degree:
package net.bounceme.dur.driver;
//import stuff
public class Server {
private static final Logger log = Logger.getLogger(Server.class.getName());
private final RecordQueue recordsQueue = new RecordQueue();
public static void main(String[] args) {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
while (true) {
try {
new Server().inOut(portNumber);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Server.class.getName()).log(Level.FINE, null, ex);
}
}
}
private List<MyRecord> dummyRecords() {
MyRecord record = null;
List<MyRecord> records = new ArrayList<>();
for (int i = 0; i < 9; i++) {
record = new MyRecord(i, "foo");
records.add(record);
log.info(record.toString());
}
return records;
}
public void inOut(int portNumber) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket socket = serverSocket.accept();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
log.info("...connected...waiting for data...");
MyRecord recordFromClient = (MyRecord) objectInputStream.readObject();
objectOutputStream.writeObject(recordFromClient);
objectOutputStream.flush();
objectInputStream.close();
objectOutputStream.close();
log.info(recordFromClient.toString());//never logs
System.out.println("never gets here");
}
}
except that it never logs the recordFromClient, which is kind of important. On the plus side, it doesn't crash.

Categories

Resources