I have problems with ByteArray and Object streams. I'm creating a multiplayer card game via NIO server. I send the ArrayList private ArrayList<Card> cardsDropped through the method:
public void sendMessage(Object message) {
if (message instanceof String) {
messages.add(message + Config.MESSAGE_DELIMITER);
} else {
messages.add(message);
}
SelectionKey key = channel.keyFor(selector);
key.interestOps(OP_WRITE);
}
With private final LinkedList<Object> messages that is the list of all objects sent in the stream through
-> Client methods:
protected void handleIncomingData(SelectionKey sender, byte[] data) throws IOException {
ByteArrayInputStream byteObject = new ByteArrayInputStream(data);
ObjectInputStream obj;
in = null;
try {
obj = new ObjectInputStream(byteObject); //HERE <--
byteObject.close();
in = obj.readObject();
obj.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
handler.onMessage(in);
}
protected void write(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel();
while (!messages.isEmpty()) {
ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(byteObject);
oos.writeObject(messages.poll());
oos.flush(); //TODO ?
oos.close();
channel.write(ByteBuffer.wrap(byteObject.toByteArray()));
byteObject.close();
} catch (IOException e) {
e.printStackTrace();
}
}
key.interestOps(OP_READ);
}
And Server methods:
protected void write(SelectionKey key) {
ByteBuffer buffer = (ByteBuffer) key.attachment();
SocketChannel channel = (SocketChannel) key.channel();
try {
channel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void handleIncomingData(SelectionKey sender, byte[] data) throws IOException {
for (SelectionKey key : selector.keys()) {
if (key.channel() instanceof ServerSocketChannel) {
continue;
}
if (key.equals(sender)) {
continue;
}
key.attach(ByteBuffer.wrap(data));
write(key);
}
}
After some turns and cards sent, Client thread is sending me some "invalid stream header" here obj = new ObjectInputStream(byteObject);
Is this a problem related to how is the server/client code written? [The code is based on https://github.com/mpkelly/nio-chat ]
Thanks in advance!
Related
It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}
I have tried sending files using java NIO socket channels according to this guide. It works fine. I modified the method to send List of files. Basically, i loop through the files list and call send method already implemented in the above-mentioned guide. There was an error "Address already in use" so I commented the socket closing line in FileSender class. After that, there was no error in the code. Seems the program stuck in middle. How do I solve this problem? is there any better way to solve the problem?
Main.Java
public static void main(String[] args) throws IOException, InterruptedException{
RunningConfiguration.run();
List<File> files = new <File>ArrayList();
File a = new File("pics/city.jpg");
File b = new File("pics/desert.jpg");
File c = new File("pics/flower.jpg");
File d = new File("pics/night.jpg");
List<Node> nodes = RunningConfiguration.getNodeList();
ListIterator li = nodes.listIterator();
while(li.hasNext()){
Node node = (Node)li.next();
FileSender.send(node, files, "pics/received/");
}
}
FileSender.Java
public class FileSender {
private final InetSocketAddress fileSocketAddress;
private final File file;
public FileSender(InetAddress inetAddress, File file) throws IOException{
this.fileSocketAddress = new InetSocketAddress(inetAddress,RunningConfiguration.FILE_PORT);
this.file = file;
}
public static void send(InetSocketAddress inetSocketAddress, File file) throws IOException{
FileSender nioClient = new FileSender(inetSocketAddress.getAddress(),file);
SocketChannel socketChannel = nioClient.createChannel();
nioClient.sendFile(socketChannel);
}
public static void send(Node to, File file) throws IOException{
FileSender nioClient = new FileSender(to.getSocketAddress().getAddress(),file);
SocketChannel socketChannel = nioClient.createChannel();
nioClient.sendFile(socketChannel);
}
public static void send(Node to, File file,String filepath) throws IOException{
FileSender nioClient = new FileSender(to.getSocketAddress().getAddress(),file);
SocketChannel socketChannel = nioClient.createChannel();
nioClient.sendFile(socketChannel);
}
public static void send(Node to,List<File> files,String filepath) throws IOException{
ListIterator ltr = files.listIterator();
while(ltr.hasNext()){
File file = (File) ltr.next();
FileSender nioClient = new FileSender(to.getSocketAddress().getAddress(),file);
SocketChannel socketChannel = nioClient.createChannel();
nioClient.sendFile(socketChannel);
}
}
public SocketChannel createChannel() {
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
SocketAddress socketAddress = this.fileSocketAddress;
socketChannel.connect(socketAddress);
System.out.println("Connected..Now sending the file");
} catch (IOException e) {
e.printStackTrace();
}
return socketChannel;
}
public void sendFile(SocketChannel socketChannel) {
RandomAccessFile aFile = null;
try {
//File file = new File("data\\web.exe");
aFile = new RandomAccessFile(this.file, "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
Thread.sleep(400);
System.out.println("End of file reached..");
socketChannel.close();
aFile.close();
} catch (FileNotFoundException e ) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
FileReceiver.java
private String fileName;
public FileReceiver(String fileName) {
this.fileName = fileName;
}
public static void receive(String fileName) {
FileReceiver nioServer = new FileReceiver(fileName);
SocketChannel socketChannel = nioServer.createServerSocketChannel();
nioServer.readFileFromSocket(socketChannel);
}
public FileReceiver() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public SocketChannel createServerSocketChannel() {
ServerSocketChannel serverSocketChannel = null;
SocketChannel socketChannel = null;
try {
System.out.println("File receiver listening at port: " + RunningConfiguration.FILE_PORT);
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(RunningConfiguration.FILE_PORT));
socketChannel = serverSocketChannel.accept();
System.out.println("Connection established...." + socketChannel.getRemoteAddress());
} catch (IOException e) {
e.printStackTrace();
}
return socketChannel;
}
/**
* Reads the bytes from socket and writes to file
*
* #param socketChannel
*/
public void readFileFromSocket(SocketChannel socketChannel) {
RandomAccessFile aFile = null;
try {
aFile = new RandomAccessFile(this.fileName, "rw");
ByteBuffer buffer = ByteBuffer.allocate(1024);
FileChannel fileChannel = aFile.getChannel();
while (socketChannel.read(buffer) > 0) {
buffer.flip();
fileChannel.write(buffer);
buffer.clear();
}
// Thread.sleep(1000);
fileChannel.close();
System.out.println("End of file reached..Closing channel");
socketChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}/*} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
You need to send the length, and probably the name, ahead of the file, so the receiver knows when to stop. The receiver has to make sure to only read exactly that many bytes, which may require reducing the limit on the last read. In addition your copy loops are incorrect:
while (inChannel.read(buffer) > 0) {
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
This doesn't necessarily work correctly at end of stream. It should be:
while (inChannel.read(buffer) >= 0 || buffer.position() > 0) {
buffer.flip();
socketChannel.write(buffer);
buffer.compact(); // NB compact(), not clear()
}
noting again that they will need further modification as described above.
I'm trying to send bytes and receive them over my socket connection but they're not doing either. I'm not sure if its a problem to do with the way i'm sending the bytes and strings or because I don't know how to read from server and client.
Client
public class Client implements Runnable {
private Socket socket;
private ByteArrayOutputStream buffer;
private OutputStream output;
private Stage stage;
public Client() {
try {
this.socket = new Socket("localhost", 1337);
this.socket.setTcpNoDelay(true);
this.socket.setKeepAlive(true);
this.output = this.socket.getOutputStream();
InputStream input = this.socket.getInputStream();
this.buffer = new ByteArrayOutputStream();
Thread connection = new Thread(this);
connection.start();
this.sendPacket(0, ByteBuffer.allocate(16 + "TEST".length()).putInt("TEST".length()).put("TEST".getBytes(Constants.UTF8)).array());
System.out.println("[CLIENT] Successfully connected to server.");
} catch (Exception e) {
IOUtils.output("[CLIENT] Error when connecting to server.");
System.exit(1337);
}
}
#Override
public void run() {
try {
while (this.connected()) {
byte[] bytes = this.buffer.toByteArray();
Constants.received += bytes.length;
if (bytes.length < 8) return;
ByteBuffer cbuf = ByteBuffer.wrap(bytes);
int size = cbuf.getInt();
int id = cbuf.getInt();
if (bytes.length < size + 8) continue;
byte[] data = Arrays.copyOfRange(bytes, 8, 8 + size);
this.processPacket(id, data);
this.buffer.close();
(this.buffer = new ByteArrayOutputStream()).write(bytes, 8 + size, bytes.length - 8 - size);
}
System.out.println("[CLIENT] Disconnected from server.");
System.exit(1337);
} catch (Exception e) {
e.printStackTrace();
}
}
private void processPacket(int id, byte[] bytes) {
ByteBuffer data = ByteBuffer.wrap(bytes);
if (id == 0) {
System.out.println("Received packet from server with id 0");
} else if (id == 1) {
System.out.println("Received packet from server with id 1");
}
}
private void sendPacket(int id, byte[] data) {
try {
ByteBuffer bytebuffer = ByteBuffer.allocate(8 + data.length);
bytebuffer.putInt(data.length);
bytebuffer.putInt(id);
bytebuffer.put(data);
byte[] bytes = bytebuffer.array();
Constants.sent += bytes.length;
this.output.write(bytes);
this.output.flush();
} catch (IOException e) {
try {
socket.close();
} catch (IOException io) {
IOUtils.output("[CLIENT] Error with client.");
System.exit(1337);
}
}
}
private boolean connected() {
return this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown() && !this.socket.isClosed();
}
}
ServerHandler
public class Handler implements Runnable {
private Socket socket;
private ByteArrayOutputStream buffer;
private OutputStream output;
public Handler(Socket socket) {
this.socket = socket;
try {
this.output = this.socket.getOutputStream();
InputStream input = this.socket.getInputStream();
this.buffer = new ByteArrayOutputStream();
Thread connection = new Thread(this);
connection.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
IOUtils.output("[HANDLER] Connection from " + socket.getInetAddress());
while (connected()) {
byte[] bytes = this.buffer.toByteArray();
if (bytes.length < 8) return;
ByteBuffer buffer = ByteBuffer.wrap(bytes);
int size = buffer.getInt();
int id = buffer.getInt();
if (bytes.length < size + 8) continue;
byte[] data = Arrays.copyOfRange(bytes, 8, 8 + size);
this.processPacket(id, data);
this.buffer.close();
(this.buffer = new ByteArrayOutputStream()).write(bytes, 8 + size, bytes.length - 8 - size);
}
IOUtils.output("[HANDLER] Client ended connection - " + socket.getInetAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendPacket(int id, byte[] data) {
try {
ByteBuffer bytebuffer = ByteBuffer.allocate(8 + data.length);
bytebuffer.putInt(data.length);
bytebuffer.putInt(id);
bytebuffer.put(data);
byte[] bytes = bytebuffer.array();
this.output.write(bytes);
this.output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processPacket(int id, byte[] bytes) {
ByteBuffer data = ByteBuffer.wrap(bytes);
if (id == 0) {
IOUtils.output("Recieved packet with id 0");
} else if (id == 1) {
//TODO: authenticate user.
}
}
private boolean connected() {
return this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown() && !this.socket.isClosed();
}
}
Server
public class Server implements Runnable {
private int port;
private ServerSocket sock;
public Server(int port) {
this.port = port;
launch();
}
private void launch() {
this.run();
}
#Override
public void run() {
try {
sock = new ServerSocket(port);
System.out.println("[SERVER] Server started");
while(!sock.isClosed()) {
new Handler(sock.accept());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think this problem might be with ByteArrayOutputStream. I wanted to use ByteBuffer because I heard it was much faster than normal DataInput and output streams.
You are never calling Socket#read inside of your run method... If you dont read anything you dont have anything to work with in your loop, even when you are connected!
Take a look at this Tutorial about Sockets:
https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
Your server code should use ServerSocket instead of Socket. Socket is used to represent Client Socket objects in Java.
Let me jump right in. Here's my Server class:
public class DTServer {
ServerSocket serverSocket;
ServerSocketHints serverSocketHints;
Socket socket;
InputStream inputStream;
OutputStream outputStream;
ObjectInputStream objectInputStream;
ObjectOutputStream objectOutputStream;
public DTServer(int port) {
serverSocketHints = new ServerSocketHints();
serverSocketHints.acceptTimeout = 0;
serverSocket = Gdx.net.newServerSocket(
Net.Protocol.TCP, port, serverSocketHints);
socket = serverSocket.accept(null);
}
public Serialized receiveSerialized() {
inputStream = socket.getInputStream();
try {
objectInputStream = new ObjectInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
outputStream = socket.getOutputStream();
try {
objectOutputStream = new ObjectOutputStream(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
Serialized serialized = new Serialized();
try {
serialized = (Serialized) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return serialized;
}
}
And the Client class:
public class DTClient {
Socket socket;
SocketHints socketHints;
InputStream inputStream;
OutputStream outputStream;
ObjectInputStream objectInputStream;
ObjectOutputStream objectOutputStream;
public DTClient(String address, int port) {
socketHints = new SocketHints();
socketHints.connectTimeout = 3000;
socketHints.keepAlive = true;
// socketHints.trafficClass = 0x04; //IPTOS_RELIABILITY
socket = Gdx.net.newClientSocket(
Net.Protocol.TCP, address, port, socketHints);
}
public void sendSerialized(Serialized serialized) {
inputStream = socket.getInputStream();
try {
objectInputStream = new ObjectInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
outputStream = socket.getOutputStream();
try {
objectOutputStream = new ObjectOutputStream(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
try {
objectOutputStream.writeObject(serialized);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I create the server object like this:
public void startServer() {
new Thread(new Runnable() {
#Override
public void run() {
dtServer = new DTServer(32658);
System.out.println("Server started and listening at port: 32658.");
}
}).start();
}
And then connect to it with other instance of the program:
public void connect() {
new Thread(new Runnable() {
#Override
public void run() {
dtClient = new DTClient("127.0.0.1", 32658);
System.out.println("Connected to server at 127.0.0.1:32658");
}
}).start();
}
And everything work swell until I try to receive the object I sent:
game.dtClient.sendSerialized(new Serialized(game.gameScreen.localPlayer));
//client side
Serialized s = (Serialized)game.dtServer.receiveSerialized();
//server side
Calling receiveSerialized method causes both app instances to freeze.
Create the ObjectOutputStream before the ObjectInputStream, at both ends. Otherwise you can get a deadlock trying to read the object stream header.
You should also use the same object streams for the life of the socket, rather than a new pair per message.
Well, I want to write a simple java client-server-programme, which exchanges byte arrays over tcp-sockets.
/* Server */
public class Server {
private ServerSocket Server = null;
private Socket Client = null;
public static void main(String[] args) {
Server A = new Server();
A.runServer();
A.listenServer();
}
public void runServer() {
try {
Server = new ServerSocket(1234);
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
System.exit(-1);
}
}
public void listenServer() {
try {
while (true) {
System.out.println("Waiting...");
Client = Server.accept();
System.out.println("Got something new");
readMessage(Client);
}
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
}
public byte [] readMessage (Socket socket) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1];
int len = -1;
while((len = socket.getInputStream().read(buf))!=-1){
baos.write(buf, 0, len);
}
for (int i=0; i<baos.toByteArray().length; i++) {
System.out.println(baos.toByteArray()[i]);
}
return baos.toByteArray();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
return null;
}
public void writeMessage (Socket socket, String Message) {
try {
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printWriter.print(Message);
printWriter.flush();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
}
}
/* Client */
public class Client {
public static void main(String[] args) {
Client B = new Client();
B.runClient();
}
public void runClient () {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 1234);
}
catch (Exception e) {
System.out.println("Client fault: "+e.getMessage());
}
byte [] Tmp = new byte[10];
for (int i=0; i<Tmp.length; i++) {
Tmp[i] = 1;
}
writeMessage(socket, Tmp);
for (int i=0; i<10; i++) {
byte [] Message = readMessage(socket);
System.out.println(Message);
}
}
public void writeMessage (Socket socket, byte [] myByteMessage) {
try {
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.write(myByteMessage, 0, myByteMessage.length);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printWriter.print(myByteMessage);
printWriter.flush();
}
catch (Exception e) {
System.out.println("Could not send data over TCP");
return;
}
}
public byte [] readMessage (Socket socket) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1];
int len = -1;
while((len = socket.getInputStream().read(buf))!=-1){
baos.write(buf, 0, len);
}
for (int i=0; i<baos.toByteArray().length; i++) {
System.out.println(baos.toByteArray()[i]);
}
System.out.println("Test");
return baos.toByteArray();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
return null;
}
}
The problem is, that the client send something to the server but the server doesn't receive anything, so he hangs at the readMessage function.
On the other hand, the client receive some weird stuff, but not the response from the server.
The server receives bytes, but it never leaves the while loop because read() never returns -1. read() returns -1 when the end of the stream is reached. And that happens only when the client closes the socket output stream. Since the client never closes the output stream, the server keeps waiting for the more bytes to come.
Side note: your code is hard to read because you don't respect the standard Java naming conventions: variables start with a lowercase letter.