[RESOLVED] reading data from SocketChannel object

import java.net.*;
import java.io.*;
import java.nio.channels.*;

public class Server {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocket = null;

try {
serverSocket = serverSocket.open();
serverSocket.configureBlocking(false);
serverSocket.socket().bind(new java.net.InetSocketAddress(5432));
SelectionKey serverkey = serverSocket.register(selector, SelectionKey.OP_ACCEPT);

} catch (IOException e) {
System.err.println("Could not listen on port: 5432.");
System.exit(1);
}

for (;;) {
selector.select();
SocketChannel clientSocket = null;

try {
clientSocket = serverSocket.accept();
clientSocket.configureBlocking(false);

//not sure what to do here to readin the incoming messages from the clients and print it on server..

} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
}
}
}

Hi guys, I need some help on how to read the incoming data and print it on the server, hope someone can help me
[1245 byte] By [pouncer] at [2007-11-20 11:24:28]
# 1 Re: [RESOLVED] reading data from SocketChannel object
AIUI, you use ServerSocketChannel.accept() to accept a connection, and you read from the SocketChannel that is returned.

See Socket Communications (http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html).

He who is ashamed of asking is ashamed of learning...
Danish proverb
dlorde at 2007-11-10 2:14:13 >
# 2 Re: [RESOLVED] reading data from SocketChannel object
Thanks dlorde, ive now changed my code to use the Selector keys to, so i can check for activity from channel sockets, im still a bit stuck;

// Get the client channel that has data to read.
SocketChannel client = (SocketChannel)key.channel();

ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = client.read(buffer);

if (read == -1) {
// Request that the registration of this key's channel with its selector be cancelled.
key.cancel();

// Close the socket-channel.
client.close();

continue;
}

else {
// How do i print the bufer data out??
}

On normal sockets, I remember being able to use something like client.getInputStream(); and it was easy to grab the incoming data, but im not sure with SocketChannel
pouncer at 2007-11-10 2:15:13 >
# 3 Re: [RESOLVED] reading data from SocketChannel object
On normal sockets, I remember being able to use something like client.getInputStream(); and it was easy to grab the incoming data, but im not sure with SocketChannelDid you look at the SocketChannel API docs? There's a method called socket() that returns the Socket...

Teachers open the door, but you must enter by yourself...
Chinese proverb.
dlorde at 2007-11-10 2:16:14 >
# 4 Re: [RESOLVED] reading data from SocketChannel object
Thanks dlorde, doing that, this is the snippet where i try to convert the socketchannel object to a socket and use socket class functions

public static void sendMessageToClients(Selector selector, SelectionKey key, String message) {
Set keys = selector.keys();

for (Iterator i = keys.iterator(); i.hasNext();) {
SelectionKey sel_key = (SelectionKey)i.next();

// We don't want to send the message to the client from which the message originally came from.
if (!sel_key.equals(key)) {
try {
SocketChannel client = (SocketChannel)sel_key.channel();
client.configureBlocking(false);

if (client.isConnected()) {

PrintWriter out = new PrintWriter(client.socket().getOutputStream(), true);
// send msg to all other clients
out.println(message);

}
} catch (IOException e) {
}
}
}
}

However, this line here:

out.println(message);

is causing errors, basically this server should send messages recevied from 1 client, to all other connected clients. The error is:

Exception in thread "main" java.lang.ClassCastException: sun.nio.ch.ServerSocket
ChannelImpl
at Server.sendMessageToClients(Server.java:127)
at Server.main(Server.java:102)

any ideas guys?
pouncer at 2007-11-10 2:17:09 >
# 5 Re: [RESOLVED] reading data from SocketChannel object
What is the code at line 127 in Server.java that is causing the ClassCastException?

Unless in communicating with it [a computer] one says exactly what one means, trouble is bound to result...
A. Turing
dlorde at 2007-11-10 2:18:08 >
# 6 Re: [RESOLVED] reading data from SocketChannel object
line 127 is this, dlorde:

SocketChannel client = (SocketChannel)sel_key.channel();

It's in the sendMessageToClients function.

and line 102 is the part where I call the function itself;

else {
String message = decode(buffer);
System.out.println("Message from client: " + message);

sendMessageToClients(selector, key, message); //line 102
}

Not sure what the problem is, I'm just trying to loop through the channel keys and get their corresponding channelsockets (connected clients) to send the message back to all these connected clients
pouncer at 2007-11-10 2:19:10 >
# 7 Re: [RESOLVED] reading data from SocketChannel object
Ok, I've managed to get rid of that exception which was being caused because it was trying to get the socketchannel for the key attached to the server socket, the server socket is actually a ServerSocketChannel, so i dealt with this by feeding the serverKey into the function too. However Im still having another problem:

public static void sendMessageToClients(Selector selector, SelectionKey key, SelectionKey serverKey, String message) {
Set keys = selector.keys();

for (Iterator i = keys.iterator(); i.hasNext();) {
SelectionKey sel_key = (SelectionKey)i.next();

try {
if (sel_key.equals(serverKey)) {
System.out.println("srver key");
//skip if server key!
continue;
}

SocketChannel client = (SocketChannel)sel_key.channel();
client.configureBlocking(false);

if (client.isConnected()) {
PrintWriter out = new PrintWriter(client.socket().getOutputStream(), true);
out.println(message); //error coming here
}
} catch (IOException e) { }

}
}

The error is at this line: out.println(message);

It's just not sending the message out to all connected clients.

Exception in thread "main" java.nio.channels.IllegalBlockingModeException
at java.nio.channels.Channels.write(Unknown Source)
at java.nio.channels.Channels.access$000(Unknown Source)
at java.nio.channels.Channels$1.write(Unknown Source)
at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(Unknown Source)
at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(Unknown Source)
at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at java.io.PrintWriter.newLine(Unknown Source)
at java.io.PrintWriter.println(Unknown Source)
at java.io.PrintWriter.println(Unknown Source)
at Server.sendMessageToClients(Server.java:147)
at Server.main(Server.java:103)
pouncer at 2007-11-10 2:20:16 >
# 8 Re: [RESOLVED] reading data from SocketChannel object
... and line 102 is the part where I call the function itself;Only the first line number of your code in the error message is relevant for the actual error itself. The other lines just tell you where the method calls are that lead to the error - it can be helpful to see what methods called the code that failed, but with a NullPointerException, you mainly want to know where you tried to access a null object.

The best is the enemy of the good...
Voltaire
dlorde at 2007-11-10 2:21:19 >