users@grizzly.java.net

Re: Newbie not getting it...

From: Oleksiy Stashok <Oleksiy.Stashok_at_Sun.COM>
Date: Tue, 11 Aug 2009 15:01:16 +0200

Hi Steve,

I've changed a little bit your MyEchoFilter:

     @Override
     public NextAction postRead(FilterChainContext ctx, NextAction
nextAction) throws IOException {
         System.out.println("READ");
         // connection, where response will be sent
         final Connection connection = ctx.getConnection();

         StreamReader reader = connection.getStreamReader();
         StreamWriter writer = connection.getStreamWriter();

         while(reader.hasAvailableData()) {
             Buffer buffer = reader.readBuffer();
             writer.writeBuffer(buffer);
         }

         return super.postRead(ctx, nextAction);
     }


cause you took UDP example as base.

Otherwise your code looks fine.

The "READ" message you always see on client - means that client
connection has some data available and you have to read it, or disable
interest in READ event:
         ((NIOConnection) connection).disableIOEvent(IOEvent.READ);
but not sure you want to do that :)

If you have any other questions - please ask.

WBR,
Alexey.


On Aug 10, 2009, at 20:37 , sasonline wrote:

>
> I forgot the code for the ChatClientHandler. I split it out in
> anticipation
> for creating a swing UI on top of it.
>
> ChatClientHandler code:
>
> import com.sun.grizzly.Connection;
> import com.sun.grizzly.TransportFactory;
> import com.sun.grizzly.nio.transport.TCPNIOTransport;
> import com.sun.grizzly.streams.StreamReader;
> import com.sun.grizzly.streams.StreamWriter;
> import java.io.IOException;
> import java.util.concurrent.ExecutionException;
> import java.util.concurrent.Future;
> import java.util.concurrent.TimeUnit;
> import java.util.logging.Level;
> import java.util.logging.Logger;
>
> /**
> *
> * @author sstacha
> */
> public class GrizzlyChatClientHandler
> {
> Connection connection = null;
> StreamReader reader = null;
> StreamWriter writer = null;
>
> // Create the TCP transport
> TCPNIOTransport transport = null;
> String host = "localhost";
> int port = 4447;
>
> public String getHost() {return host;}
> public int getPort() {return port;}
>
> public void connect(String host, int port) throws IOException
> {
> if (host != null && host.length() > 0)
> this.host = host;
> if (port > 0)
> this.port = port;
> if (transport != null)
> disconnect();
> transport =
> TransportFactory.getInstance().createTCPTransport();
> transport.getFilterChain().add(new LogFilter());
> transport.start();
>
> // perform async. connect to the server
> Future<Connection> future = transport.connect(this.host,
> this.port);
> try
> {
> // wait for connect operation to complete
> connection = future.get(10, TimeUnit.SECONDS);
>
> assert connection != null;
> }
> catch (Exception ex)
> {
> System.out.println("Exception while getting connection: "
> + ex);
> connection = null;
> }
> }
>
> public boolean sendMessage(String textMessage) throws IOException,
> InterruptedException, ExecutionException
> {
> if (connection != null && textMessage != null &&
> textMessage.length() > 0)
> {
> writer = connection.getStreamWriter();
> // byte[] sendBytes = textMessage.getBytes();
> //
> // // sync. write the complete message using
> // // temporary selectors if required
> // writer.writeByteArray(sendBytes);
> writer.writeCharArray(textMessage.toCharArray());
> Future<Integer> writeFuture = writer.flush();
> writeFuture.get();
>
> assert writeFuture.isDone();
> return true;
> }
> return false;
> }
>
> public void disconnect() throws IOException
> {
> if (connection != null)
> connection.close();
> transport.stop();
> TransportFactory.getInstance().close();
> transport = null;
> }
>
> public boolean isConnected() {return (connection != null &&
> connection.isOpen());}
> }
>
>
> sasonline wrote:
>>
>> I am trying to figure out grizzly. I thought I would start by a
>> simple
>> example where I have a server that gets a String from any client
>> and sends
>> it back out to all connected clients since there was already a
>> couple code
>> example snippits to draw from; then create a client that sends a
>> string
>> to the server and listens for strings sent from the server. To
>> keep it
>> simple I just use command line. Here is the code (using grizzly 2.0
>> library)
>>
>> Server:
>>
>> import com.sun.grizzly.TransportFactory;
>> import com.sun.grizzly.filterchain.TransportFilter;
>> import com.sun.grizzly.nio.transport.TCPNIOTransport;
>> import java.io.IOException;
>>
>> /**
>> *
>> * @author sstacha
>> */
>> public class Main
>> {
>>
>> public static final String DEFAULT_HOST = "localhost";
>> public static final int DEFAULT_PORT = 4447;
>>
>> /**
>> * @param args the command line arguments
>> */
>> public static void main(String[] args) throws IOException
>> {
>> String host;
>> try
>> {
>> host = args[0];
>> if (host == null || host.length() == 0)
>> host = DEFAULT_HOST;
>> }
>> catch (Exception ex) {host = DEFAULT_HOST;}
>> int port;
>> try {port = Integer.parseInt(args[1]);}
>> catch (Exception ex) {port = DEFAULT_PORT;}
>>
>> TCPNIOTransport transport =
>> TransportFactory.getInstance().createTCPTransport();
>> transport.getFilterChain().add(new TransportFilter());
>> transport.getFilterChain().add(new MyEchoFilter());
>> try
>> {
>> transport.bind(host, port);
>> transport.start();
>> System.out.println("[" + host + "] listening on port ["
>> + port
>> + "]");
>> System.out.println("Press <Return> to stop the
>> server...");
>> System.in.read();
>> }
>> finally
>> {
>> System.out.println("Stopping chat server...");
>> transport.stop();
>> TransportFactory.getInstance().close();
>> System.out.println("Server stopped...");
>> }
>> }
>>
>> }
>>
>> My code for MyEchoFilter (don't think this is right):
>>
>> import com.sun.grizzly.Buffer;
>> import com.sun.grizzly.Connection;
>> import com.sun.grizzly.TransformationResult;
>> import com.sun.grizzly.TransformationResult.Status;
>> import com.sun.grizzly.Transformer;
>> import com.sun.grizzly.filterchain.FilterAdapter;
>> import com.sun.grizzly.filterchain.FilterChain;
>> import com.sun.grizzly.filterchain.FilterChainContext;
>> import com.sun.grizzly.filterchain.NextAction;
>> import java.io.IOException;
>> import java.nio.charset.Charset;
>>
>> /**
>> *
>> * @author sstacha
>> */
>> public class MyEchoFilter extends FilterAdapter{
>>
>> @Override
>> public void exceptionOccurred(FilterChainContext ctx, Throwable
>> error)
>> {
>> System.out.println("EXCEPTION: " + error);
>> super.exceptionOccurred(ctx, error);
>> }
>>
>> @Override
>> public NextAction postAccept(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("ACCEPTED");
>> return super.postAccept(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postClose(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("CLOSED");
>> return super.postClose(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postConnect(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("CONNECTED");
>> return super.postConnect(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postRead(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("READ");
>> // Echo the read message
>> // incoming message
>> final Object message = ctx.getMessage();
>> // peer address
>> final Object address = ctx.getAddress();
>> // connection, where response will be sent
>> final Connection connection = ctx.getConnection();
>> // FilterChain
>> final FilterChain filterChain = ctx.getFilterChain();
>>
>> // FilterChain encoder, which will pass throw all FilterChain
>> Filters,
>> // so each of them will be able to transform the message,
>> before
>> it
>> // will be sent on a wire
>> final Transformer encoder =
>> filterChain.getCodec().getEncoder();
>>
>> // transform the message. Each CodecFilter in FilterChain is
>> able
>> // to take part in message transformation
>> TransformationResult<Buffer> result =
>> encoder.transform(connection, message, null);
>> if (result.getStatus() == Status.COMPLETED) {
>> Buffer echoMessage = result.getMessage();
>> System.out.println("Echo '" +
>> echoMessage.contentAsString(Charset.defaultCharset()) + "' address:
>> " +
>> address);
>> connection.write(address, echoMessage);
>> } else {
>> throw new IllegalStateException("Can not transform the
>> message");
>> }
>>
>> encoder.release(connection);
>>
>> return super.postRead(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postWrite(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("WRITE");
>> return super.postWrite(ctx, nextAction);
>> }
>>
>> }
>>
>> Code for client:
>>
>> import java.io.BufferedReader;
>> import java.io.IOException;
>> import java.io.InputStreamReader;
>> import java.util.concurrent.ExecutionException;
>>
>> /**
>> *
>> * @author stevestacha
>> */
>> public class Main
>> {
>> public static final String HOST = "localhost";
>> public static final int PORT = 4447;
>>
>> /**
>> * @param args the command line arguments
>> */
>> public static void main(String[] args) throws IOException,
>> InterruptedException, ExecutionException
>> {
>> GrizzlyChatClientHandler chatClient = new
>> GrizzlyChatClientHandler();
>> chatClient.connect(HOST, PORT);
>> BufferedReader inBuffer = new BufferedReader(new
>> InputStreamReader(System.in));
>> System.out.println("Type 'quit' to quit the client");
>> System.out.println("Type anything else to send the message to the
>> server");
>> String clientInput = inBuffer.readLine();
>>
>> while (!clientInput.equalsIgnoreCase("quit"))
>> {
>> chatClient.sendMessage(clientInput);
>> clientInput = inBuffer.readLine();
>> }
>> }
>>
>> }
>>
>> Code for LogFilter:
>>
>> import com.sun.grizzly.filterchain.FilterAdapter;
>> import com.sun.grizzly.filterchain.FilterChainContext;
>> import com.sun.grizzly.filterchain.NextAction;
>> import java.io.IOException;
>>
>> /**
>> *
>> * @author sstacha
>> */
>> public class LogFilter extends FilterAdapter
>> {
>>
>> @Override
>> public void exceptionOccurred(FilterChainContext ctx, Throwable
>> error)
>> {
>> System.out.println("EXCEPTION: " + error);
>> super.exceptionOccurred(ctx, error);
>> }
>>
>> @Override
>> public NextAction postAccept(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("ACCEPTED");
>> return super.postAccept(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postClose(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("CLOSED");
>> return super.postClose(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postConnect(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("CONNECTED");
>> return super.postConnect(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postRead(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("READ");
>> return super.postRead(ctx, nextAction);
>> }
>>
>> @Override
>> public NextAction postWrite(FilterChainContext ctx, NextAction
>> nextAction) throws IOException {
>> System.out.println("WRITE");
>> return super.postWrite(ctx, nextAction);
>> }
>>
>> }
>>
>> Output / Results:
>> I see the message
>> Accepted connection from java.nio.channels.SocketChannel[connected
>> local=/127.0.0.1:4447 remote=/127.0.0.1:51111]
>> on the server and CONNECTED on the client when the client starts up.
>> However, when I type a message in the client all I get is READ over
>> and
>> over again in a loop. I see nothing on the server indicating it
>> got the
>> message not even the READ that should be displayed first. I feel
>> like I
>> am missing something important. Can anyone give guidance?
>>
>> Thanks,
>>
>> Steve
>>
>>
>
> --
> View this message in context: http://www.nabble.com/Newbie-not-getting-it...-tp24904966p24905079.html
> Sent from the Grizzly - Users mailing list archive at Nabble.com.
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_grizzly.dev.java.net
> For additional commands, e-mail: users-help_at_grizzly.dev.java.net
>