xsocket-develop Mailing List for xsocket (Page 12)
Status: Inactive
Brought to you by:
grro
You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(12) |
Oct
(9) |
Nov
(11) |
Dec
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(8) |
Feb
(9) |
Mar
(9) |
Apr
(22) |
May
(28) |
Jun
(17) |
Jul
(10) |
Aug
(19) |
Sep
(4) |
Oct
(14) |
Nov
(26) |
Dec
(25) |
| 2009 |
Jan
(13) |
Feb
(17) |
Mar
(12) |
Apr
(4) |
May
(16) |
Jun
(6) |
Jul
(10) |
Aug
(24) |
Sep
(6) |
Oct
(5) |
Nov
(13) |
Dec
(10) |
| 2010 |
Jan
(17) |
Feb
(21) |
Mar
(10) |
Apr
(8) |
May
(2) |
Jun
(14) |
Jul
(7) |
Aug
(10) |
Sep
(7) |
Oct
(3) |
Nov
|
Dec
(2) |
| 2011 |
Jan
(1) |
Feb
(5) |
Mar
(1) |
Apr
|
May
(5) |
Jun
|
Jul
(2) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2014 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
(3) |
Nov
|
Dec
|
| 2015 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
|
| 2016 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(2) |
Jun
(3) |
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
| 2019 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(6) |
Sep
|
Oct
|
Nov
|
Dec
|
| 2020 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
|
From: Gregor R. <gre...@go...> - 2008-12-09 13:29:00
|
Hi,
the onConnect method will be called by xsocket (if implemented), after the
incoming client connection is established. This means if your flash-client
connects your server, the onConnect-Method will be called automatically.
Often the onConnect method is used to set connection properties (e.g. a bad
IP address -> connection.setWriteTransferRate) or to send a greeting message
to the client (e.g. smtp -> connection.write("220 mx0.gmx.net GMX
Mailservices ESMTP") )
Gregor
2008/12/9 <jun...@wp...>
> hi,
>
> My java application with xsocket server communicate with Flash client.
> Method onData works. But how to trigger onConnect method? It should be
> triggered when my Flash client connects, right? Do I have to send
> additional manually some kind of greetings message in order to trigger
> onConnnnect method?
>
> Hier is my code
>
> <Main.java>
>
> srv = new Server(8091, new xSocketDataHandler());
> srv.start();
>
> <xSocketDataHandler.java>
>
> package xsocketserver;
>
> import java.io.IOException;
> import java.nio.BufferUnderflowException;
> import java.nio.channels.ClosedChannelException;
> import org.xsocket.*;
> import org.xsocket.connection.*;
>
> public class xSocketDataHandler implements IDataHandler
>
>
> {
> public INonBlockingConnection nbc;
>
> public boolean onConnect(INonBlockingConnection nbc) throws IOException
> {
> System.out.println("Connected!!!!!");
> return true;
> }
>
> public boolean onDisconnect(INonBlockingConnection nbc) throws
> IOException {
> System.out.println("Disconected!!!!!!!!!!!!!!!!");
> return true;
> }
>
>
>
>
>
>
>
> public boolean onData(INonBlockingConnection nbc) throws IOException,
> BufferUnderflowException, ClosedChannelException,
> MaxReadSizeExceededException
> {
> try
> {
> String data = nbc.readStringByDelimiter("\0");
>
>
> System.out.println("Reciving Data");
>
>
> if(data.equalsIgnoreCase("SHUTDOWN"))
> Main.shutdownServer();
>
>
> }
> catch(Exception ex)
> {
> System.out.println(ex.getMessage());
> }
>
> return true;
> }
> }
>
> regards,
> sly
>
> ----------------------------------------------------
> Przyjdź za najlepiej ROCKUJĄCY "Sylwester z Sylwestrem"
> w Hotelu Nadmorskim w Gdyni - Kliknij:
>
> http://klik.wp.pl/?adr=http%3A%2F%2Fwww.nadmorski.pl%2Fsylwester_gdynia%2F&sid=579
>
>
>
>
> ------------------------------------------------------------------------------
> SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada.
> The future of the web can't happen without you. Join us at MIX09 to help
> pave the way to the Next Web now. Learn more and register at
>
> http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/
> _______________________________________________
> xSocket-develop mailing list
> xSo...@li...
> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
> |
|
From: <jun...@wp...> - 2008-12-09 12:04:40
|
hi,
My java application with xsocket server communicate with Flash client.
Method onData works. But how to trigger onConnect method? It should be
triggered when my Flash client connects, right? Do I have to send
additional manually some kind of greetings message in order to trigger
onConnnnect method?
Hier is my code
<Main.java>
srv = new Server(8091, new xSocketDataHandler());
srv.start();
<xSocketDataHandler.java>
package xsocketserver;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;
import org.xsocket.*;
import org.xsocket.connection.*;
public class xSocketDataHandler implements IDataHandler
{
public INonBlockingConnection nbc;
public boolean onConnect(INonBlockingConnection nbc) throws IOException {
System.out.println("Connected!!!!!");
return true;
}
public boolean onDisconnect(INonBlockingConnection nbc) throws
IOException {
System.out.println("Disconected!!!!!!!!!!!!!!!!");
return true;
}
public boolean onData(INonBlockingConnection nbc) throws IOException,
BufferUnderflowException, ClosedChannelException,
MaxReadSizeExceededException
{
try
{
String data = nbc.readStringByDelimiter("\0");
System.out.println("Reciving Data");
if(data.equalsIgnoreCase("SHUTDOWN"))
Main.shutdownServer();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
return true;
}
}
regards,
sly
----------------------------------------------------
Przyjdź za najlepiej ROCKUJĄCY "Sylwester z Sylwestrem"
w Hotelu Nadmorskim w Gdyni - Kliknij:
http://klik.wp.pl/?adr=http%3A%2F%2Fwww.nadmorski.pl%2Fsylwester_gdynia%2F&sid=579
|
|
From: Gregor R. <gre...@go...> - 2008-12-05 09:17:38
|
Hi sly,
the question is, does the client or server close the connection? You can
activate xSocket's debug log (see turorial chapter 28).
If the server closes the connection, a log message will be printed out like:
10:13:19,122 15 FINE [IoSocketHandler#readSocket]
[cf049d3a11e066c26de30ad7657C2] channel has reached end-of-stream (maybe
closed by peer)
...
cheers
Gregor
2008/12/5 <jun...@wp...>
> hi,
>
> I created NonBlockingConnection and it dies approximately after 1.5 min
> if it is not used. Is it possible set some kind of parameter to prevent
> dying if it is not used?
>
>
> nbc = new NonBlockingConnection("192.168.102.58", 12004, new
> clientHandler());
>
> regards,
> sly
>
> ----------------------------------------------------
> Co to był za GOOOOOOOOOL!
> Cyknąłeś taką akcję?
> Wrzuć foty na http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl&sid=574
>
>
>
>
> ------------------------------------------------------------------------------
> SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada.
> The future of the web can't happen without you. Join us at MIX09 to help
> pave the way to the Next Web now. Learn more and register at
>
> http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/
> _______________________________________________
> xSocket-develop mailing list
> xSo...@li...
> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
> |
|
From: <jun...@wp...> - 2008-12-05 08:45:53
|
hi,
I created NonBlockingConnection and it dies approximately after 1.5 min
if it is not used. Is it possible set some kind of parameter to prevent
dying if it is not used?
nbc = new NonBlockingConnection("192.168.102.58", 12004, new
clientHandler());
regards,
sly
----------------------------------------------------
Co to był za GOOOOOOOOOL!
Cyknąłeś taką akcję?
Wrzuć foty na http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl&sid=574
|
|
From: Gregor R. <gre...@go...> - 2008-12-05 07:12:33
|
Hi, xSocket V2.3 and xSocket-multiplexed V2.1 have been released: xSocket Release 2.3 -------------------------- a, New features: - [datagram] Endpoint - [feature request 2195400] constructor Endpoint(Map<String, Object> options, int receivePacketSize, IDatagramHandler datagramHandler, InetAddress address, int port) added - [connection] IConnectExceptionHandler added - [connection] IConnection - isServerSide() added - [connection] IBlockingConnection/INonBlockingConnection - unread(...) added - [connection] IBlockingConnection/INonBlockingConnection - write(..., IWriteCompletionHandler) added - [connection] IWriteCompletionHandler added - [connection] Server - setMaxReadBufferThreshold(...) added b, Bug fix/Implementation changes: - [connection] Property "org.xsocket.connection.dispatcher.detachHandleOnNoOps" is set to false - [connection] NonBlockingConnection - connection will be auto closed, if max read buffer size is reached and no read operation is performed - [connection] BlockingConnection/NonBlockingConnection - if the byte buffer will be reused in context of the the write(ByteBuffer)/write(ByteBuffer[]) method in FlushMode.ASYNC, a warning log message will be printed - [connection] NonBlockingConnection (ClientSide) - creating a new instance with waitForConnect=true will handled asynchronously - [datagram] BUG 'AbstractEndpoint.HandlerProcessor eats Exceptions' fixed xSocket-Multiplexed Release 2.1 ----------------------------------------- a, New features: - [connection] IWriteCompletionHandler support added b, Bug fix/Implementation changes: - [*] POM update to create a OSGI-conform jar file. Thanks to Damien for providing the patch - [*] Code cleaning based on findbugs and pmd reports - [connection] IMultiplexer - new method public void multiplex(..., IWriteCompletionHandler completionHandler) Gregor |
|
From: <jun...@wp...> - 2008-12-02 10:38:04
|
My mistake. The following code prints correct data in Hex.<br><br>String s = DataConverter.toHexString(data, available);<br>System.out.println(s);<br><br /><br /><br />----------------------------------------------------<br />Czujesz związek z Kopernikiem?! :)<br />Sprawdź swoje korzenie na bliscy.pl<br />Zbuduj drzewo swojej rodziny: <br /><A HREF="http://klik.wp.pl/?adr=http://corto.www.wp.pl/as/bliscy.html&sid=565" TARGET="_blank">http://klik.wp.pl/?adr=http://corto.www.wp.pl/as/bliscy.html&sid=565</A> |
|
From: <jun...@wp...> - 2008-12-02 10:07:54
|
Hi Gregor,<br>
<br>
I get strange output. <br>
<br>
If I expect F0 C1 01 01 01 81 00 I get 1007d 1007d 81 81 81 1007d 0 <br>
If I expect F0 C1 01 01 01 81 01 I get 1007d 1007d 81 81 81 1007d 81<br>
<br>
Do You know maybe what could be a reason ? It is correct that there is
7 bytes and the last one changes but where does those funny values came
from? I tried readStringByLength(available) and I get same wrong
output. Maybe function stringToHex doesn't work properly? Is it
possible to get Hex values from ByteBuffer[] directly?
DataConverter.toHexString(data) won't work.<br>
<br>
I wrote<br>
<br>
if (available > 0) {<br>
ByteBuffer[] data = nbc.readByteBufferByLength(available);<br>
String s = DataConverter.toString(data);<br>
System.out.println(stringToHex(s));<br>
return true;<br>
<br>
//and I use this function to convert to Hex<br>
<br>
public static String stringToHex(String base)<br>
{<br>
StringBuffer buffer = new StringBuffer();<br>
int intValue;<br>
for(int x = 0; x < base.length(); x++)<br>
{<br>
int cursor = 0;<br>
intValue = base.charAt(x);<br>
String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));<br>
for(int i = 0; i < binaryChar.length(); i++)<br>
{<br>
if(binaryChar.charAt(i) == '1')<br>
{<br>
cursor += 1;<br>
}<br>
}<br>
if((cursor % 2) > 0)<br>
{<br>
intValue += 128;<br>
}<br>
buffer.append(Integer.toHexString(intValue) + " ");<br>
}<br>
return buffer.toString();<br>
}<br>
<br>
<br>
<br><br /><br /><br />----------------------------------------------------<br />Czujesz związek z Kopernikiem?! :)<br />Sprawdź swoje korzenie na bliscy.pl<br />Zbuduj drzewo swojej rodziny: <br /><A HREF="http://klik.wp.pl/?adr=http://corto.www.wp.pl/as/bliscy.html&sid=565" TARGET="_blank">http://klik.wp.pl/?adr=http://corto.www.wp.pl/as/bliscy.html&sid=565</A>
|
|
From: Gregor R. <gre...@go...> - 2008-12-01 21:23:32
|
Hi, ByteBuffer[] is a reference to an array. To print it out you can use the DataConverter.toString(Bytebuffer[]) method. Please note, after printing the data to buffer internal pointers will will modified. If you like to use a String instead of ByteBuffer you can call the readStringByLength(available) instead of readByteBufferByLength(available). See also xSocket's tutorial http://xsocket.sourceforge.net/core/tutorial/V2/TutorialCore.htm Gregor 2008/12/1 <jun...@wp...> > Hi Gregor, > > So If I understand it correctly if I append System.out.println(data); > like this > > if (available > 0) { > ByteBuffer[] data = connection.readByteBufferByLength(available); > System.out.println(data); > return true; > > then I should be able to display all data from the frame that i have > just received. right? > > The Problem is I get this: > > [Ljava.nio.ByteBuffer;@126b249 > > and I'm expecting something like this > > f086010000 > > Is it some kind of pointer/referance? How do I access the real value? Is > there any method like data.getValue etc or I have to split string and so > on? > > regards, > sly > > > > Dnia 1-12-2008 o godz. 16:32 Gregor Roth napisał(a): > > Hi sly, > > > > the method connection.available() return the available bytes. Typically > you will read all available like this: > > > > ////////////////////// > > // > > > > public boolean onData(INonBlockingConnection connection) > > int available = connection.available(); > > > > if (available > 0) { > > ByteBuffer[] data = connection.readByteBufferByLength(available); > > // ... > > return true; > > > > } if (available == -1) { > > // connection is closed > > // ... > > return true; > > } > > } > > > > // > > //////////////////////////////// > > > > If available returns -1 the end of stream is reached. > > > > Gregor > > > > > > > > 2008/12/1 <jun...@wp...> > > > hi, > > > > > > What method should I use to read whole data field of incoming Ethernet > > > frame? I tried readByteBufferByDelimiter but I'm not sure how to > specify > > > delimiter. I want to read all bytes in data field. How to set delimiter > > > to read data until there is no more data? > > > > > > ByteBuffer[] res2 = nbc.readByteBufferByDelimiter(""); > > > System.out.println(res2); > > > > > > regards, > > > sly > > > > > > ---------------------------------------------------- > > > Pstryk i klik. > > > Na Pikeo.pl szybko zamieszczasz swoje najlepsze zdjęcia: > > > > http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl%2Finstances%2Fwp%2Fstrona_01.jsp&sid=557 > > > > > > > > > > > > > ------------------------------------------------------------------------- > > > This SF.Net email is sponsored by the Moblin Your Move Developer's > challenge > > > Build the coolest Linux based applications with Moblin SDK & win great > prizes > > > Grand prize is a trip for two to an Open Source event anywhere in the > world > > > http://moblin-contest.org/redirect.php?banner_id=100&url=/ > > > _______________________________________________ > > > xSocket-develop mailing list > > > xSo...@li... > > > https://lists.sourceforge.net/lists/listinfo/xsocket-develop > > > > > > > ---------------------------------------------------- > Pstryk i klik. > Na Pikeo.pl szybko zamieszczasz swoje najlepsze zdjęcia: > > http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl%2Finstances%2Fwp%2Fstrona_01.jsp&sid=557 > > > |
|
From: <jun...@wp...> - 2008-12-01 16:30:18
|
Hi Gregor,
So If I understand it correctly if I append System.out.println(data);
like this
if (available > 0) {
ByteBuffer[] data = connection.readByteBufferByLength(available);
System.out.println(data);
return true;
then I should be able to display all data from the frame that i have
just received. right?
The Problem is I get this:
[Ljava.nio.ByteBuffer;@126b249
and I'm expecting something like this
f086010000
Is it some kind of pointer/referance? How do I access the real value? Is
there any method like data.getValue etc or I have to split string and so
on?
regards,
sly
Dnia 1-12-2008 o godz. 16:32 Gregor Roth napisał(a):
> Hi sly,
>
> the method connection.available() return the available bytes. Typically
you will read all available like this:
>
> //////////////////////
> //
>
> public boolean onData(INonBlockingConnection connection)
> int available = connection.available();
>
> if (available > 0) {
> ByteBuffer[] data = connection.readByteBufferByLength(available);
> // ...
> return true;
>
> } if (available == -1) {
> // connection is closed
> // ...
> return true;
> }
> }
>
> //
> ////////////////////////////////
>
> If available returns -1 the end of stream is reached.
>
> Gregor
>
>
>
> 2008/12/1 <jun...@wp...>
> > hi,
> >
> > What method should I use to read whole data field of incoming Ethernet
> > frame? I tried readByteBufferByDelimiter but I'm not sure how to specify
> > delimiter. I want to read all bytes in data field. How to set delimiter
> > to read data until there is no more data?
> >
> > ByteBuffer[] res2 = nbc.readByteBufferByDelimiter("");
> > System.out.println(res2);
> >
> > regards,
> > sly
> >
> > ----------------------------------------------------
> > Pstryk i klik.
> > Na Pikeo.pl szybko zamieszczasz swoje najlepsze zdjęcia:
> > http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl%2Finstances%2Fwp%2Fstrona_01.jsp&sid=557
> >
> >
> >
> > -------------------------------------------------------------------------
> > This SF.Net email is sponsored by the Moblin Your Move Developer's
challenge
> > Build the coolest Linux based applications with Moblin SDK & win great
prizes
> > Grand prize is a trip for two to an Open Source event anywhere in the
world
> > http://moblin-contest.org/redirect.php?banner_id=100&url=/
> > _______________________________________________
> > xSocket-develop mailing list
> > xSo...@li...
> > https://lists.sourceforge.net/lists/listinfo/xsocket-develop
> >
>
----------------------------------------------------
Pstryk i klik.
Na Pikeo.pl szybko zamieszczasz swoje najlepsze zdjęcia:
http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl%2Finstances%2Fwp%2Fstrona_01.jsp&sid=557
|
|
From: Gregor R. <gre...@go...> - 2008-12-01 15:32:06
|
Hi sly,
the method connection.available() return the available bytes. Typically you
will read all available like this:
//////////////////////
//
public boolean onData(INonBlockingConnection connection)
int available = connection.available();
if (available > 0) {
ByteBuffer[] data = connection.readByteBufferByLength(available);
// ...
return true;
} if (available == -1) {
// connection is closed
// ...
return true;
}
}
//
////////////////////////////////
If available returns -1 the end of stream is reached.
Gregor
2008/12/1 <jun...@wp...>
> hi,
>
> What method should I use to read whole data field of incoming Ethernet
> frame? I tried readByteBufferByDelimiter but I'm not sure how to specify
> delimiter. I want to read all bytes in data field. How to set delimiter
> to read data until there is no more data?
>
> ByteBuffer[] res2 = nbc.readByteBufferByDelimiter("");
> System.out.println(res2);
>
> regards,
> sly
>
> ----------------------------------------------------
> Pstryk i klik.
> Na Pikeo.pl szybko zamieszczasz swoje najlepsze zdjęcia:
>
> http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl%2Finstances%2Fwp%2Fstrona_01.jsp&sid=557
>
>
>
> -------------------------------------------------------------------------
> This SF.Net email is sponsored by the Moblin Your Move Developer's
> challenge
> Build the coolest Linux based applications with Moblin SDK & win great
> prizes
> Grand prize is a trip for two to an Open Source event anywhere in the world
> http://moblin-contest.org/redirect.php?banner_id=100&url=/
> _______________________________________________
> xSocket-develop mailing list
> xSo...@li...
> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
> |
|
From: <jun...@wp...> - 2008-12-01 10:52:16
|
hi,
What method should I use to read whole data field of incoming Ethernet
frame? I tried readByteBufferByDelimiter but I'm not sure how to specify
delimiter. I want to read all bytes in data field. How to set delimiter
to read data until there is no more data?
ByteBuffer[] res2 = nbc.readByteBufferByDelimiter("");
System.out.println(res2);
regards,
sly
----------------------------------------------------
Pstryk i klik.
Na Pikeo.pl szybko zamieszczasz swoje najlepsze zdjęcia:
http://klik.wp.pl/?adr=http%3A%2F%2Fpikeo.pl%2Finstances%2Fwp%2Fstrona_01.jsp&sid=557
|
|
From: Gregor R. <gre...@go...> - 2008-11-28 18:22:31
|
Hi Gregor, I agree with you. I'm gonig to fix this. I´m sorry for your pain ;-) Gregor 2008/11/28 gk <gk...@ph...> > Hi.. > > I ran across the following Problem in case a uncaught Exception is > thrown in a IDatagramHandler, like a RuntimeException, it is very very > hard to detect. > The usual way we handle this kind of Exceptions is to register a default > UncaughtExceptionHandler on the Thread class. It contains logic to deal > with the Exception and report them accordingly. > Now in case IDatagramHandler throws such a Exception it is catched and > eaten by run() in AbstractEndpoint.HandlerProcessor. > As far as I know it is not recommended to silently catch away > exceptions, specially for a API used by others this could lead to > confusion and troubles to find errors. Everything appears to be fine > even though errors occur. > I would suggest/recommend to throw the caught Exception again after > handling it. So that it pops up as uncaught exception on the Thread. > This way xSocket API users can see error and handle the Exception > accordingly. > > Regards, > Gregor > > ------------------------------------------------------------------------- > This SF.Net email is sponsored by the Moblin Your Move Developer's > challenge > Build the coolest Linux based applications with Moblin SDK & win great > prizes > Grand prize is a trip for two to an Open Source event anywhere in the world > http://moblin-contest.org/redirect.php?banner_id=100&url=/ > _______________________________________________ > xSocket-develop mailing list > xSo...@li... > https://lists.sourceforge.net/lists/listinfo/xsocket-develop > |
|
From: gk <gk...@ph...> - 2008-11-28 10:18:47
|
Hi.. I ran across the following Problem in case a uncaught Exception is thrown in a IDatagramHandler, like a RuntimeException, it is very very hard to detect. The usual way we handle this kind of Exceptions is to register a default UncaughtExceptionHandler on the Thread class. It contains logic to deal with the Exception and report them accordingly. Now in case IDatagramHandler throws such a Exception it is catched and eaten by run() in AbstractEndpoint.HandlerProcessor. As far as I know it is not recommended to silently catch away exceptions, specially for a API used by others this could lead to confusion and troubles to find errors. Everything appears to be fine even though errors occur. I would suggest/recommend to throw the caught Exception again after handling it. So that it pops up as uncaught exception on the Thread. This way xSocket API users can see error and handle the Exception accordingly. Regards, Gregor |
|
From: <jun...@wp...> - 2008-11-28 08:49:23
|
Hi Gregor,<br><br>Thank You for Your response. Well my task is simple. In my Java program I want to access any time (not only while onData event) existing Nonblocking connection in order to send some messages to the client. The Problem is that I have 2 connections (one on port 8091 and the second one on port 8090) and I don't know how to distinguish them. The both are called nbc. Only the server names are different (srv and srv2) but accessing nbc using server name ie. srv.nbc.write("abc") or
srv2.nbc.write("") doesen't work. <br><br>My program works as follows: Main function creates 2 servers (srv and srv2) on two different ports (8091 and 8090). onData function in class xSocketDataHandler sends easy echo response to the client. It is actually not really importatnt what it does right now. I have to write function which will handle incomming data in the future. This is that function splitString in Main which is calld within onData class. Right now this function splitString
does nothing with the string but I wanted to try if I can send some data over existing nbc using that function. And I can't sand any data. I don't know why. <br><br>package xsocketserver;<br>
<br>
import org.xsocket.connection.*;<br>
import org.jdom.input.SAXBuilder;<br>
import org.jdom.Document;<br>
import org.jdom.JDOMException;<br>
import org.jdom.Element;<br>
import org.jdom.output.XMLOutputter;<br>
import org.jdom.Attribute;<br>
import java.io.*;<br>
//import xSocketDataHandler.*;<br>
<br>
<br>
public class Main<br>
{<br>
protected static IServer srv = null;<br>
protected static IServer srv2 = null;<br>
public static Document doc;<br>
public static Element webapp;<br>
public static INonBlockingConnection nbc;<br>
public static xSocketDataHandler srvHandler;<br>
<br>
public static void main(String[] args)<br>
{<br>
<br>
<br>
<br>
try<br>
{<br>
//nbc1 = new NonBlockingConnection("<a href="http://127.0.0.1" target="_blank">127.0.0.1</a>", 8092);<br>
srvHandler = new xSocketDataHandler();<br>
<br>
srv = new Server(8091, srvHandler);<br>
srv.start();<br>
srv2 = new Server(8090, new xSocketDataHandler());<br>
srv2.start();<br>
<br>
//nbc = new NonBlockingConnection(srvHandler);<br>
//nbc1.write("aaaaaaabbbbbbbaaaaa" + "\0");<br>
<br>
}<br>
catch(Exception ex)<br>
{<br>
System.out.println(ex.getMessage());<br>
}<br>
<br>
<br>
<br>
<br>
}<br>
<br>
<br>
public static void stringSplit(String str)<br>
{<br>
try<br>
{ <br><br> nbc.write("some text");<br>
//xSocketDataHandler obj = new xSocketDataHandler();<br>
//obj.onData(true).nbc.write("dsfds");<br>
//srvHandler obj = new srvHandler();<br>
//obj.nbc.write("trele morele" + "\0");<br>
//nbc1.write("aaaaaaa" + "\0");<br>
}<br>
catch(Exception ex)<br>
{<br>
System.out.println(ex.getMessage());<br>
}<br>
}<br><br><br>package xsocketserver;<br>
<br>
import java.io.IOException;<br>
import java.nio.BufferUnderflowException;<br>
import java.nio.channels.ClosedChannelException;<br>
import org.xsocket.*;<br>
import org.xsocket.connection.*;<br><br>
public class xSocketDataHandler implements IDataHandler<br>
<br>
<br>
{<br>
public INonBlockingConnection nbc;<br>
<br>
public boolean onData(INonBlockingConnection nbc) throws IOException,<br>
BufferUnderflowException, ClosedChannelException,<br>
MaxReadSizeExceededException<br>
{<br>
try<br>
{<br>
String data = nbc.readStringByDelimiter("\0");<br>
Main.stringSplit(data);<br>
nbc.write(data + "\0");<br>
//nbc.write("trele morele" + "\0");<br>
<br>
}<br>
catch(Exception ex)<br>
{<br>
System.out.println(ex.getMessage());<br>
}<br>
<br>
return true;<br>
}<br><br>regards,<br>sly<br><br>Dnia 27-11-2008 o godz. 21:58 Gregor Roth napisał(a):
<blockquote style="border-left: 1px solid rgb(204, 204, 204); margin: 0px 0px 0px 0.8ex; padding-left: 1ex;">Hi sly,<br><br>your code snippets are quite confusing. May be it helps that you describe what you intent to do.<br><br>regards<br>Gregor <br><br><br></blockquote><br><br /><br /><br />----------------------------------------------------<br />Spadł pierwszy śnieg, więc wybieramy się na narty. Jedziesz z nami?<br />TUTAJ wszystko o szusowaniu - kliknij: <br /><A HREF="http://klik.wp.pl/?adr=http://narty.wp.pl&sid=571" TARGET="_blank">http://klik.wp.pl/?adr=http://narty.wp.pl&sid=571</A>
|
|
From: Gregor R. <gre...@go...> - 2008-11-27 20:58:43
|
Hi sly,
your code snippets are quite confusing. May be it helps that you describe
what you intent to do.
regards
Gregor
2008/11/27 <jun...@wp...>
> I still can't figure out what is wrong. Please, I really need Your help
> on this one. I somebody would have time to help me I would be grateful.
> Thank You in advance.
>
> sly
>
> Dnia 26-11-2008 o godz. 9:55 dytu iuyr napisał(a):
> > hi,
> >
> > I have a problem. I can't send data using nbc.write("some text") to a
> > client from function in my main class. How can I select the connection
> > that I want to use if there are 2 different?
> >
> > In my main function in my main class of my java program I created two
> > servers which are maintaining two different nbc on different sockets.
> >
> > srvHandler = new xSocketDataHandler();
> > srv = new Server(8091, srvHandler);
> > srv.start();
> > srv2 = new Server(8090, new xSocketDataHandler());
> > srv2.start();
> >
> >
> > As You can see, xSocketDataHandler is another simple class (in file
> > xSocketDataHandler.java) with onData function only. It looks like this:
> >
> > package xsocketserver;
> >
> > import java.io.IOException;
> > import java.nio.BufferUnderflowException;
> > import java.nio.channels.ClosedChannelException;
> > import org.xsocket.*;
> > import org.xsocket.connection.*;
> >
> > public class xSocketDataHandler implements IDataHandler
> >
> >
> > {
> > public INonBlockingConnection nbc;
> >
> > public boolean onData(INonBlockingConnection nbc) throws IOException,
> > BufferUnderflowException, ClosedChannelException,
> > MaxReadSizeExceededException
> > {
> > try
> > {
> > String data = nbc.readStringByDelimiter("\0");
> > Main.stringSplit(data);
> > nbc.write(data + "\0");
> > //nbc.write("trele morele" + "\0");
> >
> > }
> > catch(Exception ex)
> > {
> > System.out.println(ex.getMessage());
> > }
> >
> > return true;
> > }
> >
> >
> > Now I want to access nbc from function StringSplit in my main class and
> > be able to send some data for example to the client on the another side
> > of connection on socket 8091, independently from onData function (now
> > sending data works only in this function). I set nbc to public in
> > xSocketDataHandler class and I tried many different ways of accessing
> > that nbc but doesn't mater what I do, the client doesn't receive data.
> >
> >
> > package xsocketserver;
> >
> > import org.xsocket.connection.*;
> > import org.jdom.input.SAXBuilder;
> > import org.jdom.Document;
> > import org.jdom.JDOMException;
> > import org.jdom.Element;
> > import org.jdom.output.XMLOutputter;
> > import org.jdom.Attribute;
> > import java.io.*;
> > //import xSocketDataHandler.*;
> >
> >
> > public class Main
> > {
> > protected static IServer srv = null;
> > protected static IServer srv2 = null;
> > public static Document doc;
> > public static Element webapp;
> > public static INonBlockingConnection nbc;
> > public static xSocketDataHandler srvHandler;
> >
> > public static void main(String[] args)
> > {
> >
> >
> >
> > try
> > {
> > //nbc1 = new NonBlockingConnection("127.0.0.1", 8092);
> > srvHandler = new xSocketDataHandler();
> >
> > srv = new Server(8091, srvHandler);
> > srv.start();
> > srv2 = new Server(8090, new xSocketDataHandler());
> > srv2.start();
> >
> > //nbc = new NonBlockingConnection(srvHandler);
> > //nbc1.write("aaaaaaabbbbbbbaaaaa" + "\0");
> >
> > }
> > catch(Exception ex)
> > {
> > System.out.println(ex.getMessage());
> > }
> >
> >
> >
> >
> > }
> >
> >
> > public static void stringSplit(String str)
> > {
> > try
> > { nbc.write("some text");
> > //xSocketDataHandler obj = new xSocketDataHandler();
> > //obj.onData(true).nbc.write("dsfds");
> > //srvHandler obj = new srvHandler();
> > //obj.nbc.write("trele morele" + "\0");
> > //nbc1.write("aaaaaaa" + "\0");
> > }
> > catch(Exception ex)
> > {
> > System.out.println(ex.getMessage());
> > }
> > }
> >
> > ----------------------------------------------------
> > Uważaj na drodze:
> >
> http://klik.wp.pl/?adr=http%3A%2F%2Fprorocznia.pl%2Ff.html%3Fi%3D37169O-283747030O0&sid=568
> >
> >
> >
> > -------------------------------------------------------------------------
> > This SF.Net email is sponsored by the Moblin Your Move Developer's
> > challenge
> > Build the coolest Linux based applications with Moblin SDK & win great
> > prizes
> > Grand prize is a trip for two to an Open Source event anywhere in the
> > world
> > http://moblin-contest.org/redirect.php?banner_id=100&url=/
> > _______________________________________________
> > xSocket-develop mailing list
> > xSo...@li...
> > https://lists.sourceforge.net/lists/listinfo/xsocket-develop
>
> ----------------------------------------------------
> Fascynujący labirynt Carlosa Ruiza Zafona, autora Cienia wiatru:
> świat Barcelony, mroczne sekrety i Cmentarz Zapomnianych Książek w
> najnowszej powieści pt. "Gra anioła"!
>
> http://klik.wp.pl/?adr=http%3A%2F%2Fcorto.www.wp.pl%2Fas%2Fgraaniola.html&sid=569
>
>
>
> -------------------------------------------------------------------------
> This SF.Net email is sponsored by the Moblin Your Move Developer's
> challenge
> Build the coolest Linux based applications with Moblin SDK & win great
> prizes
> Grand prize is a trip for two to an Open Source event anywhere in the world
> http://moblin-contest.org/redirect.php?banner_id=100&url=/
> _______________________________________________
> xSocket-develop mailing list
> xSo...@li...
> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
> |
|
From: <jun...@wp...> - 2008-11-27 08:06:35
|
I still can't figure out what is wrong. Please, I really need Your help
on this one. I somebody would have time to help me I would be grateful.
Thank You in advance.
sly
Dnia 26-11-2008 o godz. 9:55 dytu iuyr napisał(a):
> hi,
>
> I have a problem. I can't send data using nbc.write("some text") to a
> client from function in my main class. How can I select the connection
> that I want to use if there are 2 different?
>
> In my main function in my main class of my java program I created two
> servers which are maintaining two different nbc on different sockets.
>
> srvHandler = new xSocketDataHandler();
> srv = new Server(8091, srvHandler);
> srv.start();
> srv2 = new Server(8090, new xSocketDataHandler());
> srv2.start();
>
>
> As You can see, xSocketDataHandler is another simple class (in file
> xSocketDataHandler.java) with onData function only. It looks like this:
>
> package xsocketserver;
>
> import java.io.IOException;
> import java.nio.BufferUnderflowException;
> import java.nio.channels.ClosedChannelException;
> import org.xsocket.*;
> import org.xsocket.connection.*;
>
> public class xSocketDataHandler implements IDataHandler
>
>
> {
> public INonBlockingConnection nbc;
>
> public boolean onData(INonBlockingConnection nbc) throws IOException,
> BufferUnderflowException, ClosedChannelException,
> MaxReadSizeExceededException
> {
> try
> {
> String data = nbc.readStringByDelimiter("\0");
> Main.stringSplit(data);
> nbc.write(data + "\0");
> //nbc.write("trele morele" + "\0");
>
> }
> catch(Exception ex)
> {
> System.out.println(ex.getMessage());
> }
>
> return true;
> }
>
>
> Now I want to access nbc from function StringSplit in my main class and
> be able to send some data for example to the client on the another side
> of connection on socket 8091, independently from onData function (now
> sending data works only in this function). I set nbc to public in
> xSocketDataHandler class and I tried many different ways of accessing
> that nbc but doesn't mater what I do, the client doesn't receive data.
>
>
> package xsocketserver;
>
> import org.xsocket.connection.*;
> import org.jdom.input.SAXBuilder;
> import org.jdom.Document;
> import org.jdom.JDOMException;
> import org.jdom.Element;
> import org.jdom.output.XMLOutputter;
> import org.jdom.Attribute;
> import java.io.*;
> //import xSocketDataHandler.*;
>
>
> public class Main
> {
> protected static IServer srv = null;
> protected static IServer srv2 = null;
> public static Document doc;
> public static Element webapp;
> public static INonBlockingConnection nbc;
> public static xSocketDataHandler srvHandler;
>
> public static void main(String[] args)
> {
>
>
>
> try
> {
> //nbc1 = new NonBlockingConnection("127.0.0.1", 8092);
> srvHandler = new xSocketDataHandler();
>
> srv = new Server(8091, srvHandler);
> srv.start();
> srv2 = new Server(8090, new xSocketDataHandler());
> srv2.start();
>
> //nbc = new NonBlockingConnection(srvHandler);
> //nbc1.write("aaaaaaabbbbbbbaaaaa" + "\0");
>
> }
> catch(Exception ex)
> {
> System.out.println(ex.getMessage());
> }
>
>
>
>
> }
>
>
> public static void stringSplit(String str)
> {
> try
> { nbc.write("some text");
> //xSocketDataHandler obj = new xSocketDataHandler();
> //obj.onData(true).nbc.write("dsfds");
> //srvHandler obj = new srvHandler();
> //obj.nbc.write("trele morele" + "\0");
> //nbc1.write("aaaaaaa" + "\0");
> }
> catch(Exception ex)
> {
> System.out.println(ex.getMessage());
> }
> }
>
> ----------------------------------------------------
> Uważaj na drodze:
> http://klik.wp.pl/?adr=http%3A%2F%2Fprorocznia.pl%2Ff.html%3Fi%3D37169O-283747030O0&sid=568
>
>
>
> -------------------------------------------------------------------------
> This SF.Net email is sponsored by the Moblin Your Move Developer's
> challenge
> Build the coolest Linux based applications with Moblin SDK & win great
> prizes
> Grand prize is a trip for two to an Open Source event anywhere in the
> world
> http://moblin-contest.org/redirect.php?banner_id=100&url=/
> _______________________________________________
> xSocket-develop mailing list
> xSo...@li...
> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
----------------------------------------------------
Fascynujący labirynt Carlosa Ruiza Zafona, autora Cienia wiatru:
świat Barcelony, mroczne sekrety i Cmentarz Zapomnianych Książek w
najnowszej powieści pt. "Gra anioła"!
http://klik.wp.pl/?adr=http%3A%2F%2Fcorto.www.wp.pl%2Fas%2Fgraaniola.html&sid=569
|
|
From: dytu i. <jun...@wp...> - 2008-11-26 08:55:39
|
hi,
I have a problem. I can't send data using nbc.write("some text") to a
client from function in my main class. How can I select the connection
that I want to use if there are 2 different?
In my main function in my main class of my java program I created two
servers which are maintaining two different nbc on different sockets.
srvHandler = new xSocketDataHandler();
srv = new Server(8091, srvHandler);
srv.start();
srv2 = new Server(8090, new xSocketDataHandler());
srv2.start();
As You can see, xSocketDataHandler is another simple class (in file
xSocketDataHandler.java) with onData function only. It looks like this:
package xsocketserver;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;
import org.xsocket.*;
import org.xsocket.connection.*;
public class xSocketDataHandler implements IDataHandler
{
public INonBlockingConnection nbc;
public boolean onData(INonBlockingConnection nbc) throws IOException,
BufferUnderflowException, ClosedChannelException,
MaxReadSizeExceededException
{
try
{
String data = nbc.readStringByDelimiter("\0");
Main.stringSplit(data);
nbc.write(data + "\0");
//nbc.write("trele morele" + "\0");
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
return true;
}
Now I want to access nbc from function StringSplit in my main class and
be able to send some data for example to the client on the another side
of connection on socket 8091, independently from onData function (now
sending data works only in this function). I set nbc to public in
xSocketDataHandler class and I tried many different ways of accessing
that nbc but doesn't mater what I do, the client doesn't receive data.
package xsocketserver;
import org.xsocket.connection.*;
import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.Attribute;
import java.io.*;
//import xSocketDataHandler.*;
public class Main
{
protected static IServer srv = null;
protected static IServer srv2 = null;
public static Document doc;
public static Element webapp;
public static INonBlockingConnection nbc;
public static xSocketDataHandler srvHandler;
public static void main(String[] args)
{
try
{
//nbc1 = new NonBlockingConnection("127.0.0.1", 8092);
srvHandler = new xSocketDataHandler();
srv = new Server(8091, srvHandler);
srv.start();
srv2 = new Server(8090, new xSocketDataHandler());
srv2.start();
//nbc = new NonBlockingConnection(srvHandler);
//nbc1.write("aaaaaaabbbbbbbaaaaa" + "\0");
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
public static void stringSplit(String str)
{
try
{ nbc.write("some text");
//xSocketDataHandler obj = new xSocketDataHandler();
//obj.onData(true).nbc.write("dsfds");
//srvHandler obj = new srvHandler();
//obj.nbc.write("trele morele" + "\0");
//nbc1.write("aaaaaaa" + "\0");
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
----------------------------------------------------
Uważaj na drodze:
http://klik.wp.pl/?adr=http%3A%2F%2Fprorocznia.pl%2Ff.html%3Fi%3D37169O-283747030O0&sid=568
|
|
From: Gregor R. <gre...@go...> - 2008-11-25 10:34:23
|
Hi, you are using the run() method to start the server. The run() method is a blocking method, this means you will never return from srv.run() (until the server stops). The srv2.run() will not be called in your code. The Server class also supports a start() method which returns after the server is started. Following code should work srv = new Server(8090, new xSocketDataHandler()); srv.start(); srv2 = new Server(8091, new xSocketDataHandler()); srv2.run(); For a more detailed explanation refer to xSocket'S tutorial: http://xsocket.sourceforge.net/core/tutorial/V2/TutorialCore.htm Gregor 2008/11/25 dytu iuyr <jun...@wp...> > hello, > > I'm student and I'm working on some project. I'm sorry if its not the > right place for posting my question but I couldn't find any forum > regarding xSocket. Anyway my problem is as follows: I want to control > some kind of gateway using Flash interface. Between Flash interface and > gateway there is java program with xSocket running. Thanks to great > tutorial of Chad Lung on this site: > http://giantflyingsaucer.com/blog/?p=205 i was able to establish > connection between interface and java program. Now I'm trying to > establish second simultaneous socket connection with that gateway. I'm > not sure if my approach is right (I have no experience in writing > network app) but I'm trying to create another server with another name > which will listen for incoming messages on another socket. As You can > see it is simple modification of tutorial. The problem is although I > don't get any error it doesn't work. Can someone have a look at my code > and tell me what is wrong with it? Thank You in advance. > > Here is my code: > > package xsocketserver; > > import org.xsocket.connection.*; > > public class Main > { > protected static IServer srv = null; > protected static IServer srv2 = null; > > public static void main(String[] args) > { > try > { > srv = new Server(8090, new xSocketDataHandler()); > srv.run(); > srv2 = new Server(8091, new xSocketDataHandler()); > srv2.run(); > > } > catch(Exception ex) > { > System.out.println(ex.getMessage()); > } > } > > protected static void shutdownServer() > { > try > { > srv.close(); > } > catch(Exception ex) > { > System.out.println(ex.getMessage()); > } > } > } > > > package xsocketserver; > > import java.io.IOException; > import java.nio.BufferUnderflowException; > import java.nio.channels.ClosedChannelException; > import org.xsocket.*; > import org.xsocket.connection.*; > > public class xSocketDataHandler implements IDataHandler > { > > public boolean onData(INonBlockingConnection nbc) throws IOException, > BufferUnderflowException, ClosedChannelException, > MaxReadSizeExceededException > { > try > { > String data = nbc.readStringByDelimiter("\0"); > nbc.write(data + "\0"); > > if(data.equalsIgnoreCase("SHUTDOWN")) > Main.shutdownServer(); > } > catch(Exception ex) > { > System.out.println(ex.getMessage()); > } > > return true; > } > } > > ---------------------------------------------------- > Zbuduj drzewo genealogiczne swojej rodziny! > Sprawdź jakie to łatwe i proste :) > Zacznij już teraz: > > http://klik.wp.pl/?adr=http%3A%2F%2Fcorto.www.wp.pl%2Fas%2Fbliscy.html&sid=567 > > > > ------------------------------------------------------------------------- > This SF.Net email is sponsored by the Moblin Your Move Developer's > challenge > Build the coolest Linux based applications with Moblin SDK & win great > prizes > Grand prize is a trip for two to an Open Source event anywhere in the world > http://moblin-contest.org/redirect.php?banner_id=100&url=/ > _______________________________________________ > xSocket-develop mailing list > xSo...@li... > https://lists.sourceforge.net/lists/listinfo/xsocket-develop > |
|
From: dytu i. <jun...@wp...> - 2008-11-25 09:12:17
|
hello, I'm student and I'm working on some project. I'm sorry if its not the right place for posting my question but I couldn't find any forum regarding xSocket. Anyway my problem is as follows: I want to control some kind of gateway using Flash interface. Between Flash interface and gateway there is java program with xSocket running. Thanks to great tutorial of Chad Lung on this site: http://giantflyingsaucer.com/blog/?p=205 i was able to establish connection between interface and java program. Now I'm trying to establish second simultaneous socket connection with that gateway. I'm not sure if my approach is right (I have no experience in writing network app) but I'm trying to create another server with another name which will listen for incoming messages on another socket. As You can see it is simple modification of tutorial. The problem is although I don't get any error it doesn't work. Can someone have a look at my code and tell me what is wrong with it? Thank You in advance. Here is my code: package xsocketserver; import org.xsocket.connection.*; public class Main { protected static IServer srv = null; protected static IServer srv2 = null; public static void main(String[] args) { try { srv = new Server(8090, new xSocketDataHandler()); srv.run(); srv2 = new Server(8091, new xSocketDataHandler()); srv2.run(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } protected static void shutdownServer() { try { srv.close(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } } package xsocketserver; import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.channels.ClosedChannelException; import org.xsocket.*; import org.xsocket.connection.*; public class xSocketDataHandler implements IDataHandler { public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException { try { String data = nbc.readStringByDelimiter("\0"); nbc.write(data + "\0"); if(data.equalsIgnoreCase("SHUTDOWN")) Main.shutdownServer(); } catch(Exception ex) { System.out.println(ex.getMessage()); } return true; } } ---------------------------------------------------- Zbuduj drzewo genealogiczne swojej rodziny! Sprawdź jakie to łatwe i proste :) Zacznij już teraz: http://klik.wp.pl/?adr=http%3A%2F%2Fcorto.www.wp.pl%2Fas%2Fbliscy.html&sid=567 |
|
From: beijing w. <wel...@gm...> - 2008-11-24 03:45:34
|
2008/11/22 Gregor Roth <gre...@go...>
> Hi,
>
> by using the pool, the retrieved connection should always be closed after
> using it. The close method returns the connection into the pool. If an error
> is occurred by using the connection, the connection should be destroyed by
> calling the pool's destroy method to avoid that the connection will be
> returned into the pool (the pool internal always checks if the returned
> connection is healthy, however it is a good behaviour to destroy the
> connection if it is known that an error is occurred).
oh, yes, it did InetSocketAddress(host, port) every time, when reaching the
max active connection number, it will retrieve the connection in the pool.
why not reuse the connection for each connection, anyway, it's not a general
client solution, the client which need transfer several files in a very
short time need to do that, and other client such as chat, also need to
reuse the connection.
>
> Regarding to interoperable communication I do have no specific hints for
> you
you have helped me a lot here.
>
>
> Gregor
>
>
> 2008/11/19 beijing welcome <wel...@gm...>
>
> Gregor, thanks you so much for your great help again!
>>
>> two minor basic questions about client implements.
>>
>> 1. about BlockingConnectionPool
>>
>> client {
>> private final BlockingConnectionPool pool = new
>> BlockingConnectionPool();
>> public void *read*(filename) {
>> try {
>> con = pool.getBlockingConnection(host, port);
>> // do something...
>> } catch () {
>> // the TCP connection is still kept, i mena when this function was
>> called for many times in for loop,
>> // it still keep the same connection, not waste resource here. right?
>> pool.destroy(con);
>> }
>> }
>>
>> void main() {
>> for (int i = 0; i < size; i++) {
>> client.*read*(files[i]);
>> }
>> }
>> }
>>
>>
>> 2. if the client is implemented by C++ or other language, any tricky
>> issues for the connection?
>>
>>
>>
>> 2008/11/19 Gregor Roth <gre...@go...>
>>
>> Hi,
>>>
>>> I'm not sure if I understand your code. The DataHander is used to send
>>> the file to the client. On the other side the DataHandler will be used by
>>> handling the data command (which is used to upload data from the client to
>>> the server?)
>>>
>>> I added a simple FileServer into the test trunk of xSocket. See
>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServer.javaand
>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServerClient.java
>>>
>>> May be it helps you to write your server
>>>
>>> Gregor
>>>
>>>
>>>
>>> 2008/11/18 beijing welcome <wel...@gm...>
>>>
>>> hi, Gregor,
>>>> many thanks for your suggestion, i tried to do.
>>>>
>>>> the code below were copied from SimpleSmtpClient.java and
>>>> SimpleSmtpServer.java, for some reason, it didn't work.
>>>> i'm in trouble in the filechannel parts, which were comments in *bold*below.
>>>> could you please point me out what's the error?
>>>>
>>>>
>>>> ========== SimplePicClient.java ============
>>>> package picserver;
>>>>
>>>> import java.io.File;
>>>> import java.io.FileInputStream;
>>>> import java.io.IOException;
>>>> import java.io.RandomAccessFile;
>>>> import java.nio.BufferUnderflowException;
>>>> import java.nio.channels.FileChannel;
>>>> import java.util.logging.ConsoleHandler;
>>>> import java.util.logging.Level;
>>>> import java.util.logging.Logger;
>>>>
>>>>
>>>> import org.xsocket.LogFormatter;
>>>> import org.xsocket.MaxReadSizeExceededException;
>>>> import org.xsocket.connection.BlockingConnection;
>>>> import org.xsocket.connection.IBlockingConnection;
>>>>
>>>>
>>>> public final class SimplePicClient {
>>>>
>>>> private static final Logger LOG =
>>>> Logger.getLogger(SimplePicClient.class.getName());
>>>>
>>>>
>>>> private String host = null;
>>>> private int port = -1;
>>>>
>>>> public static void main(String[] args) throws Exception {
>>>>
>>>> Logger logger =
>>>> Logger.getLogger(SimplePicClient.class.getName());
>>>> logger.setLevel(Level.FINE);
>>>>
>>>> ConsoleHandler ch = new ConsoleHandler();
>>>> ch.setLevel(Level.FINE);
>>>> ch.setFormatter(new LogFormatter());
>>>> logger.addHandler(ch);
>>>>
>>>> String host = "127.0.0.1";
>>>> int port = 9527;
>>>>
>>>> SimplePicClient smtpClient = new SimplePicClient(host, port);
>>>> smtpClient.send();
>>>> }
>>>>
>>>>
>>>>
>>>> public SimplePicClient(String host, int port) throws IOException {
>>>> this.host = host;
>>>> this.port = port;
>>>> }
>>>>
>>>>
>>>>
>>>> public void send() throws IOException {
>>>>
>>>> IBlockingConnection con = new BlockingConnection(host, port);
>>>>
>>>> // read greeting
>>>> readResponse(con);
>>>>
>>>> sendCmd(con, "Helo you");
>>>> readResponse(con);
>>>>
>>>> sendCmd(con, "Data");
>>>> readFileResponse(con);
>>>> con.write("\r\n.\r\n");
>>>>
>>>>
>>>> sendCmd(con, "Quit");
>>>> readResponse(con);
>>>>
>>>> con.close();
>>>> }
>>>>
>>>>
>>>> private void sendCmd(IBlockingConnection con, String cmd) throws
>>>> IOException {
>>>> LOG.fine("sending " + cmd);
>>>> con.write(cmd + "\r\n");
>>>> }
>>>>
>>>> private String readResponse(IBlockingConnection con) throws
>>>> IOException {
>>>> String response = con.readStringByDelimiter("\r\n");
>>>> LOG.fine("receiving " + response);
>>>>
>>>> return response;
>>>> }
>>>>
>>>> * private String readFileResponse(IBlockingConnection con)
>>>> throws IOException, BufferUnderflowException,
>>>> MaxReadSizeExceededException {
>>>>
>>>> int length = con.readInt();
>>>> // the output is:
>>>> // 24:54:06,359 10 FINE [SimplePicClient#readFileResponse] length:
>>>> 1164866661
>>>> LOG.fine("length: " + length);
>>>> FileChannel fc = new RandomAccessFile(
>>>> "D:\\1\\tmp.txt", "rw").getChannel();
>>>> fc.transferTo(0, length, con);
>>>> fc.close();
>>>> return "Done";
>>>> }*
>>>> }
>>>>
>>>> ============== SimplePicServer.java =================
>>>> package picserver;
>>>>
>>>> import java.io.File;
>>>> import java.io.IOException;
>>>> import java.io.RandomAccessFile;
>>>> import java.nio.BufferUnderflowException;
>>>> import java.nio.channels.FileChannel;
>>>>
>>>> import org.xsocket.Execution;
>>>> import org.xsocket.MaxReadSizeExceededException;
>>>> import org.xsocket.connection.IConnectHandler;
>>>> import org.xsocket.connection.IDataHandler;
>>>> import org.xsocket.connection.INonBlockingConnection;
>>>> import org.xsocket.connection.IServer;
>>>> import org.xsocket.connection.Server;
>>>> import org.xsocket.connection.ConnectionUtils;
>>>> import org.xsocket.connection.IConnection.FlushMode;
>>>>
>>>>
>>>> public final class SimplePicServer extends Server {
>>>>
>>>>
>>>> public static void main(String[] args) throws Exception {
>>>> int port = 9527;
>>>> String outDir = "c://tmp";
>>>> if (!new File(outDir).exists()) {
>>>> System.out.println(outDir + " does not exists. creating
>>>> directory");
>>>> new File(outDir).mkdirs();
>>>> }
>>>>
>>>> System.out.println("writing mails to directory " + outDir);
>>>>
>>>> IServer server = new SimplePicServer(port, outDir);
>>>> server.setFlushMode(FlushMode.ASYNC);
>>>> // server.start();
>>>> ConnectionUtils.registerMBean(server);
>>>> server.run();
>>>> }
>>>>
>>>>
>>>> public SimplePicServer(int port, String outDir) throws IOException {
>>>> super(port, new SimplePicHandler(outDir));
>>>> }
>>>>
>>>> @Execution(Execution.NONTHREADED)
>>>> private static final class SimplePicHandler
>>>> implements IConnectHandler, IDataHandler {
>>>>
>>>> private String msgFileDir = null;
>>>> private int countReceivedMessages = 0;
>>>>
>>>> public SimplePicHandler(String msgFileDir) {
>>>> this.msgFileDir = msgFileDir;
>>>> }
>>>>
>>>>
>>>>
>>>> public boolean onConnect(INonBlockingConnection connection)
>>>> throws IOException, BufferUnderflowException,
>>>> MaxReadSizeExceededException {
>>>> connection.write("220 ready \r\n");
>>>>
>>>> return true;
>>>> }
>>>>
>>>>
>>>> public boolean onData(INonBlockingConnection connection)
>>>> throws IOException, BufferUnderflowException,
>>>> MaxReadSizeExceededException {
>>>>
>>>> String cmd =
>>>> connection.readStringByDelimiter("\r\n").toUpperCase();
>>>> System.out.println(cmd);
>>>> if (cmd.startsWith("HELO")) {
>>>> connection.write("250 Service\r\n");
>>>> System.out.println("when HELO");
>>>> } else if(cmd.equals("DATA")) {
>>>> File msgFile = new File("D:\\1\\mail.txt");
>>>> connection.setHandler(
>>>> new DataHandler(msgFile, this));
>>>> connection.write("Enter message, ending with
>>>> \".\"\r\n");
>>>>
>>>> System.out.println("when DATA");
>>>>
>>>> } else if (cmd.startsWith("QUIT")) {
>>>> connection.write("221 service closing connection\r\n");
>>>> connection.close();
>>>> System.out.println("when QUIT");
>>>>
>>>> } else {
>>>> connection.write("500 Unrecognized command\r\n");
>>>> System.out.println("when else");
>>>>
>>>> }
>>>>
>>>> return true;
>>>> }
>>>>
>>>>
>>>> String getMessageFileDirectory() {
>>>> return msgFileDir;
>>>> }
>>>>
>>>> void setMessageFileDirectory(String msgFileDir) {
>>>> this.msgFileDir = msgFileDir;
>>>> }
>>>>
>>>> int getCountReceivedMessages() {
>>>> return countReceivedMessages;
>>>> }
>>>>
>>>> void incCountReceiveMessages() {
>>>> countReceivedMessages++;
>>>> }
>>>> }
>>>>
>>>>
>>>> @Execution(Execution.MULTITHREADED)
>>>> private static final class DataHandler implements IDataHandler {
>>>>
>>>> private SimplePicHandler simplePicHandler;
>>>> private File file;
>>>> private FileChannel fc;
>>>>
>>>> public DataHandler(File file, SimplePicHandler simplePicHandler)
>>>> {
>>>> this.file = file;
>>>> this.simplePicHandler = simplePicHandler;
>>>> }
>>>>
>>>> * public boolean onData(INonBlockingConnection connection)
>>>> throws IOException, BufferUnderflowException,
>>>> MaxReadSizeExceededException {
>>>>
>>>> if (fc == null) {
>>>> fc = new RandomAccessFile(file, "r").getChannel();
>>>> }
>>>> int length = (int)fc.size();
>>>> System.out.println("length: " + length);
>>>> connection.write(length);
>>>> connection.transferFrom(fc);
>>>> fc.close();
>>>> fc = null;
>>>> // it's not correct, the handler here failed to go back to
>>>> SimplePicHandler
>>>> // the following command are all dealed by DataHandler, which should be
>>>> dealed by SimplePicHandler.
>>>> connection.setHandler(simplePicHandler);
>>>> connection.write("250 OK\r\n");
>>>> return true;
>>>> }*
>>>> }
>>>>
>>>> }
>>>>
>>>>
>>>>
>>>> 2008/11/18 Gregor Roth <gre...@go...>
>>>>
>>>> Hi,
>>>>>
>>>>> in most cases it is better to use the multithreaded mode (multithreaded
>>>>> is the default mode). Running the service in a non-threaded mode is a
>>>>> performance optimization. However, the non-threaded mode will work only
>>>>> work, if the handler doesn't perform I/O operations such as file or network
>>>>> operations.
>>>>>
>>>>> To avoid outstanding threads while receiving file data, you could read
>>>>> the network data and write it to a file in a non-blocking mode. For instance
>>>>> see the Data Handler of the SimpleSmtpServer ->
>>>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleSmtpServer.java
>>>>>
>>>>> To send a file a sync mode has to be used. For instance see the
>>>>> UploadHandler2 of the SimpleFileChannelPerformanceTest >
>>>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileChannelPerformanceTest.java
>>>>> With Java 1.7 you will have the option to access the file in an async
>>>>> mode. In this case you can use a non-blocking, async approach similar to the
>>>>> file upload scenario.
>>>>>
>>>>> If the server reaches the limit by serving many clients, a transport
>>>>> level load balancing solution will be used to spread the request over a farm
>>>>> of servers. For a more detailed explanation see link
>>>>> http://www.javaworld.com/javaworld/jw-10-2008/jw-10-load-balancing-1.html
>>>>>
>>>>> Gregor
>>>>>
>>>>>
>>>>>
>>>>>
>>>>>
>>>>> 2008/11/17 beijing welcome <wel...@gm...>
>>>>>
>>>>>> hi,
>>>>>> a discussion for applying xSocket to implement an effective and robust
>>>>>> file server.
>>>>>>
>>>>>> a TCP server stores lots of small pictures (from 1k to 5k for each
>>>>>> size).
>>>>>> a client downloads pictures from server frequently, but seldom do
>>>>>> uploading job.
>>>>>>
>>>>>> as far as i know for xSocket, the server can use
>>>>>> SERVER: transferFrom a FileChannel to BlockingConnection in on
>>>>>> IDataHandler.onData()
>>>>>> CLIENT: can use transferTo a FileChannel from BlockingConnection
>>>>>>
>>>>>> the communication between client and server has two steps:
>>>>>> 1. client sends a query to server, server send back the pictures list
>>>>>> which need to download.
>>>>>> 2. client begins to download the pictures from server.
>>>>>>
>>>>>> if the client need to download more than 10 pictures in a seconds,
>>>>>> then it seems reasonable to use multi thread.
>>>>>>
>>>>>> the question is how to design in server side.
>>>>>> 1) if use multi thread, how to write the IDataHandler.onData()? if
>>>>>> it's BlockingConnection, will it block other threads for this connection? if
>>>>>> NonBlockingConnection, need to write to bytebuffer.duplicate()?
>>>>>>
>>>>>> 2) if many clients connect to the same server (e.g. more than 10k),
>>>>>> the multi thread will rise the connection number? how to minimize the load
>>>>>> of server? if use proxy to do load balance, any other problem?
>>>>>>
>>>>>>
>>>>>>
>>>>>> what's your opinion?
>>>>>>
>>>>>> any comments are appreciated.
>>>>>>
>>>>>>
>>>>>> -------------------------------------------------------------------------
>>>>>> This SF.Net email is sponsored by the Moblin Your Move Developer's
>>>>>> challenge
>>>>>> Build the coolest Linux based applications with Moblin SDK & win great
>>>>>> prizes
>>>>>> Grand prize is a trip for two to an Open Source event anywhere in the
>>>>>> world
>>>>>> http://moblin-contest.org/redirect.php?banner_id=100&url=/
>>>>>> _______________________________________________
>>>>>> xSocket-develop mailing list
>>>>>> xSo...@li...
>>>>>> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
>>>>>>
>>>>>>
>>>>>
>>>>
>>>
>>
> |
|
From: Gregor R. <gre...@go...> - 2008-11-21 17:50:15
|
Hi,
by using the pool, the retrieved connection should always be closed after
using it. The close method returns the connection into the pool. If an error
is occurred by using the connection, the connection should be destroyed by
calling the pool's destroy method to avoid that the connection will be
returned into the pool (the pool internal always checks if the returned
connection is healthy, however it is a good behaviour to destroy the
connection if it is known that an error is occurred).
Regarding to interoperable communication I do have no specific hints for you
Gregor
2008/11/19 beijing welcome <wel...@gm...>
> Gregor, thanks you so much for your great help again!
>
> two minor basic questions about client implements.
>
> 1. about BlockingConnectionPool
>
> client {
> private final BlockingConnectionPool pool = new BlockingConnectionPool();
> public void *read*(filename) {
> try {
> con = pool.getBlockingConnection(host, port);
> // do something...
> } catch () {
> // the TCP connection is still kept, i mena when this function was
> called for many times in for loop,
> // it still keep the same connection, not waste resource here. right?
> pool.destroy(con);
> }
> }
>
> void main() {
> for (int i = 0; i < size; i++) {
> client.*read*(files[i]);
> }
> }
> }
>
>
> 2. if the client is implemented by C++ or other language, any tricky issues
> for the connection?
>
>
>
> 2008/11/19 Gregor Roth <gre...@go...>
>
> Hi,
>>
>> I'm not sure if I understand your code. The DataHander is used to send the
>> file to the client. On the other side the DataHandler will be used by
>> handling the data command (which is used to upload data from the client to
>> the server?)
>>
>> I added a simple FileServer into the test trunk of xSocket. See
>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServer.javaand
>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServerClient.java
>>
>> May be it helps you to write your server
>>
>> Gregor
>>
>>
>>
>> 2008/11/18 beijing welcome <wel...@gm...>
>>
>> hi, Gregor,
>>> many thanks for your suggestion, i tried to do.
>>>
>>> the code below were copied from SimpleSmtpClient.java and
>>> SimpleSmtpServer.java, for some reason, it didn't work.
>>> i'm in trouble in the filechannel parts, which were comments in *bold*below.
>>> could you please point me out what's the error?
>>>
>>>
>>> ========== SimplePicClient.java ============
>>> package picserver;
>>>
>>> import java.io.File;
>>> import java.io.FileInputStream;
>>> import java.io.IOException;
>>> import java.io.RandomAccessFile;
>>> import java.nio.BufferUnderflowException;
>>> import java.nio.channels.FileChannel;
>>> import java.util.logging.ConsoleHandler;
>>> import java.util.logging.Level;
>>> import java.util.logging.Logger;
>>>
>>>
>>> import org.xsocket.LogFormatter;
>>> import org.xsocket.MaxReadSizeExceededException;
>>> import org.xsocket.connection.BlockingConnection;
>>> import org.xsocket.connection.IBlockingConnection;
>>>
>>>
>>> public final class SimplePicClient {
>>>
>>> private static final Logger LOG =
>>> Logger.getLogger(SimplePicClient.class.getName());
>>>
>>>
>>> private String host = null;
>>> private int port = -1;
>>>
>>> public static void main(String[] args) throws Exception {
>>>
>>> Logger logger =
>>> Logger.getLogger(SimplePicClient.class.getName());
>>> logger.setLevel(Level.FINE);
>>>
>>> ConsoleHandler ch = new ConsoleHandler();
>>> ch.setLevel(Level.FINE);
>>> ch.setFormatter(new LogFormatter());
>>> logger.addHandler(ch);
>>>
>>> String host = "127.0.0.1";
>>> int port = 9527;
>>>
>>> SimplePicClient smtpClient = new SimplePicClient(host, port);
>>> smtpClient.send();
>>> }
>>>
>>>
>>>
>>> public SimplePicClient(String host, int port) throws IOException {
>>> this.host = host;
>>> this.port = port;
>>> }
>>>
>>>
>>>
>>> public void send() throws IOException {
>>>
>>> IBlockingConnection con = new BlockingConnection(host, port);
>>>
>>> // read greeting
>>> readResponse(con);
>>>
>>> sendCmd(con, "Helo you");
>>> readResponse(con);
>>>
>>> sendCmd(con, "Data");
>>> readFileResponse(con);
>>> con.write("\r\n.\r\n");
>>>
>>>
>>> sendCmd(con, "Quit");
>>> readResponse(con);
>>>
>>> con.close();
>>> }
>>>
>>>
>>> private void sendCmd(IBlockingConnection con, String cmd) throws
>>> IOException {
>>> LOG.fine("sending " + cmd);
>>> con.write(cmd + "\r\n");
>>> }
>>>
>>> private String readResponse(IBlockingConnection con) throws
>>> IOException {
>>> String response = con.readStringByDelimiter("\r\n");
>>> LOG.fine("receiving " + response);
>>>
>>> return response;
>>> }
>>>
>>> * private String readFileResponse(IBlockingConnection con)
>>> throws IOException, BufferUnderflowException,
>>> MaxReadSizeExceededException {
>>>
>>> int length = con.readInt();
>>> // the output is:
>>> // 24:54:06,359 10 FINE [SimplePicClient#readFileResponse] length:
>>> 1164866661
>>> LOG.fine("length: " + length);
>>> FileChannel fc = new RandomAccessFile(
>>> "D:\\1\\tmp.txt", "rw").getChannel();
>>> fc.transferTo(0, length, con);
>>> fc.close();
>>> return "Done";
>>> }*
>>> }
>>>
>>> ============== SimplePicServer.java =================
>>> package picserver;
>>>
>>> import java.io.File;
>>> import java.io.IOException;
>>> import java.io.RandomAccessFile;
>>> import java.nio.BufferUnderflowException;
>>> import java.nio.channels.FileChannel;
>>>
>>> import org.xsocket.Execution;
>>> import org.xsocket.MaxReadSizeExceededException;
>>> import org.xsocket.connection.IConnectHandler;
>>> import org.xsocket.connection.IDataHandler;
>>> import org.xsocket.connection.INonBlockingConnection;
>>> import org.xsocket.connection.IServer;
>>> import org.xsocket.connection.Server;
>>> import org.xsocket.connection.ConnectionUtils;
>>> import org.xsocket.connection.IConnection.FlushMode;
>>>
>>>
>>> public final class SimplePicServer extends Server {
>>>
>>>
>>> public static void main(String[] args) throws Exception {
>>> int port = 9527;
>>> String outDir = "c://tmp";
>>> if (!new File(outDir).exists()) {
>>> System.out.println(outDir + " does not exists. creating
>>> directory");
>>> new File(outDir).mkdirs();
>>> }
>>>
>>> System.out.println("writing mails to directory " + outDir);
>>>
>>> IServer server = new SimplePicServer(port, outDir);
>>> server.setFlushMode(FlushMode.ASYNC);
>>> // server.start();
>>> ConnectionUtils.registerMBean(server);
>>> server.run();
>>> }
>>>
>>>
>>> public SimplePicServer(int port, String outDir) throws IOException {
>>> super(port, new SimplePicHandler(outDir));
>>> }
>>>
>>> @Execution(Execution.NONTHREADED)
>>> private static final class SimplePicHandler
>>> implements IConnectHandler, IDataHandler {
>>>
>>> private String msgFileDir = null;
>>> private int countReceivedMessages = 0;
>>>
>>> public SimplePicHandler(String msgFileDir) {
>>> this.msgFileDir = msgFileDir;
>>> }
>>>
>>>
>>>
>>> public boolean onConnect(INonBlockingConnection connection)
>>> throws IOException, BufferUnderflowException,
>>> MaxReadSizeExceededException {
>>> connection.write("220 ready \r\n");
>>>
>>> return true;
>>> }
>>>
>>>
>>> public boolean onData(INonBlockingConnection connection)
>>> throws IOException, BufferUnderflowException,
>>> MaxReadSizeExceededException {
>>>
>>> String cmd =
>>> connection.readStringByDelimiter("\r\n").toUpperCase();
>>> System.out.println(cmd);
>>> if (cmd.startsWith("HELO")) {
>>> connection.write("250 Service\r\n");
>>> System.out.println("when HELO");
>>> } else if(cmd.equals("DATA")) {
>>> File msgFile = new File("D:\\1\\mail.txt");
>>> connection.setHandler(
>>> new DataHandler(msgFile, this));
>>> connection.write("Enter message, ending with \".\"\r\n");
>>>
>>> System.out.println("when DATA");
>>>
>>> } else if (cmd.startsWith("QUIT")) {
>>> connection.write("221 service closing connection\r\n");
>>> connection.close();
>>> System.out.println("when QUIT");
>>>
>>> } else {
>>> connection.write("500 Unrecognized command\r\n");
>>> System.out.println("when else");
>>>
>>> }
>>>
>>> return true;
>>> }
>>>
>>>
>>> String getMessageFileDirectory() {
>>> return msgFileDir;
>>> }
>>>
>>> void setMessageFileDirectory(String msgFileDir) {
>>> this.msgFileDir = msgFileDir;
>>> }
>>>
>>> int getCountReceivedMessages() {
>>> return countReceivedMessages;
>>> }
>>>
>>> void incCountReceiveMessages() {
>>> countReceivedMessages++;
>>> }
>>> }
>>>
>>>
>>> @Execution(Execution.MULTITHREADED)
>>> private static final class DataHandler implements IDataHandler {
>>>
>>> private SimplePicHandler simplePicHandler;
>>> private File file;
>>> private FileChannel fc;
>>>
>>> public DataHandler(File file, SimplePicHandler simplePicHandler)
>>> {
>>> this.file = file;
>>> this.simplePicHandler = simplePicHandler;
>>> }
>>>
>>> * public boolean onData(INonBlockingConnection connection)
>>> throws IOException, BufferUnderflowException,
>>> MaxReadSizeExceededException {
>>>
>>> if (fc == null) {
>>> fc = new RandomAccessFile(file, "r").getChannel();
>>> }
>>> int length = (int)fc.size();
>>> System.out.println("length: " + length);
>>> connection.write(length);
>>> connection.transferFrom(fc);
>>> fc.close();
>>> fc = null;
>>> // it's not correct, the handler here failed to go back to
>>> SimplePicHandler
>>> // the following command are all dealed by DataHandler, which should be
>>> dealed by SimplePicHandler.
>>> connection.setHandler(simplePicHandler);
>>> connection.write("250 OK\r\n");
>>> return true;
>>> }*
>>> }
>>>
>>> }
>>>
>>>
>>>
>>> 2008/11/18 Gregor Roth <gre...@go...>
>>>
>>> Hi,
>>>>
>>>> in most cases it is better to use the multithreaded mode (multithreaded
>>>> is the default mode). Running the service in a non-threaded mode is a
>>>> performance optimization. However, the non-threaded mode will work only
>>>> work, if the handler doesn't perform I/O operations such as file or network
>>>> operations.
>>>>
>>>> To avoid outstanding threads while receiving file data, you could read
>>>> the network data and write it to a file in a non-blocking mode. For instance
>>>> see the Data Handler of the SimpleSmtpServer ->
>>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleSmtpServer.java
>>>>
>>>> To send a file a sync mode has to be used. For instance see the
>>>> UploadHandler2 of the SimpleFileChannelPerformanceTest –>
>>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileChannelPerformanceTest.java
>>>> With Java 1.7 you will have the option to access the file in an async
>>>> mode. In this case you can use a non-blocking, async approach similar to the
>>>> file upload scenario.
>>>>
>>>> If the server reaches the limit by serving many clients, a transport
>>>> level load balancing solution will be used to spread the request over a farm
>>>> of servers. For a more detailed explanation see link
>>>> http://www.javaworld.com/javaworld/jw-10-2008/jw-10-load-balancing-1.html
>>>>
>>>> Gregor
>>>>
>>>>
>>>>
>>>>
>>>>
>>>> 2008/11/17 beijing welcome <wel...@gm...>
>>>>
>>>>> hi,
>>>>> a discussion for applying xSocket to implement an effective and robust
>>>>> file server.
>>>>>
>>>>> a TCP server stores lots of small pictures (from 1k to 5k for each
>>>>> size).
>>>>> a client downloads pictures from server frequently, but seldom do
>>>>> uploading job.
>>>>>
>>>>> as far as i know for xSocket, the server can use
>>>>> SERVER: transferFrom a FileChannel to BlockingConnection in on
>>>>> IDataHandler.onData()
>>>>> CLIENT: can use transferTo a FileChannel from BlockingConnection
>>>>>
>>>>> the communication between client and server has two steps:
>>>>> 1. client sends a query to server, server send back the pictures list
>>>>> which need to download.
>>>>> 2. client begins to download the pictures from server.
>>>>>
>>>>> if the client need to download more than 10 pictures in a seconds, then
>>>>> it seems reasonable to use multi thread.
>>>>>
>>>>> the question is how to design in server side.
>>>>> 1) if use multi thread, how to write the IDataHandler.onData()? if it's
>>>>> BlockingConnection, will it block other threads for this connection? if
>>>>> NonBlockingConnection, need to write to bytebuffer.duplicate()?
>>>>>
>>>>> 2) if many clients connect to the same server (e.g. more than 10k), the
>>>>> multi thread will rise the connection number? how to minimize the load of
>>>>> server? if use proxy to do load balance, any other problem?
>>>>>
>>>>>
>>>>>
>>>>> what's your opinion?
>>>>>
>>>>> any comments are appreciated.
>>>>>
>>>>>
>>>>> -------------------------------------------------------------------------
>>>>> This SF.Net email is sponsored by the Moblin Your Move Developer's
>>>>> challenge
>>>>> Build the coolest Linux based applications with Moblin SDK & win great
>>>>> prizes
>>>>> Grand prize is a trip for two to an Open Source event anywhere in the
>>>>> world
>>>>> http://moblin-contest.org/redirect.php?banner_id=100&url=/
>>>>> _______________________________________________
>>>>> xSocket-develop mailing list
>>>>> xSo...@li...
>>>>> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
>>>>>
>>>>>
>>>>
>>>
>>
>
|
|
From: beijing w. <wel...@gm...> - 2008-11-19 15:02:30
|
Gregor, thanks you so much for your great help again!
two minor basic questions about client implements.
1. about BlockingConnectionPool
client {
private final BlockingConnectionPool pool = new BlockingConnectionPool();
public void *read*(filename) {
try {
con = pool.getBlockingConnection(host, port);
// do something...
} catch () {
// the TCP connection is still kept, i mena when this function was
called for many times in for loop,
// it still keep the same connection, not waste resource here. right?
pool.destroy(con);
}
}
void main() {
for (int i = 0; i < size; i++) {
client.*read*(files[i]);
}
}
}
2. if the client is implemented by C++ or other language, any tricky issues
for the connection?
2008/11/19 Gregor Roth <gre...@go...>
> Hi,
>
> I'm not sure if I understand your code. The DataHander is used to send the
> file to the client. On the other side the DataHandler will be used by
> handling the data command (which is used to upload data from the client to
> the server?)
>
> I added a simple FileServer into the test trunk of xSocket. See
> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServer.javaand
> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServerClient.java
>
> May be it helps you to write your server
>
> Gregor
>
>
>
> 2008/11/18 beijing welcome <wel...@gm...>
>
> hi, Gregor,
>> many thanks for your suggestion, i tried to do.
>>
>> the code below were copied from SimpleSmtpClient.java and
>> SimpleSmtpServer.java, for some reason, it didn't work.
>> i'm in trouble in the filechannel parts, which were comments in *bold*below.
>> could you please point me out what's the error?
>>
>>
>> ========== SimplePicClient.java ============
>> package picserver;
>>
>> import java.io.File;
>> import java.io.FileInputStream;
>> import java.io.IOException;
>> import java.io.RandomAccessFile;
>> import java.nio.BufferUnderflowException;
>> import java.nio.channels.FileChannel;
>> import java.util.logging.ConsoleHandler;
>> import java.util.logging.Level;
>> import java.util.logging.Logger;
>>
>>
>> import org.xsocket.LogFormatter;
>> import org.xsocket.MaxReadSizeExceededException;
>> import org.xsocket.connection.BlockingConnection;
>> import org.xsocket.connection.IBlockingConnection;
>>
>>
>> public final class SimplePicClient {
>>
>> private static final Logger LOG =
>> Logger.getLogger(SimplePicClient.class.getName());
>>
>>
>> private String host = null;
>> private int port = -1;
>>
>> public static void main(String[] args) throws Exception {
>>
>> Logger logger = Logger.getLogger(SimplePicClient.class.getName());
>> logger.setLevel(Level.FINE);
>>
>> ConsoleHandler ch = new ConsoleHandler();
>> ch.setLevel(Level.FINE);
>> ch.setFormatter(new LogFormatter());
>> logger.addHandler(ch);
>>
>> String host = "127.0.0.1";
>> int port = 9527;
>>
>> SimplePicClient smtpClient = new SimplePicClient(host, port);
>> smtpClient.send();
>> }
>>
>>
>>
>> public SimplePicClient(String host, int port) throws IOException {
>> this.host = host;
>> this.port = port;
>> }
>>
>>
>>
>> public void send() throws IOException {
>>
>> IBlockingConnection con = new BlockingConnection(host, port);
>>
>> // read greeting
>> readResponse(con);
>>
>> sendCmd(con, "Helo you");
>> readResponse(con);
>>
>> sendCmd(con, "Data");
>> readFileResponse(con);
>> con.write("\r\n.\r\n");
>>
>>
>> sendCmd(con, "Quit");
>> readResponse(con);
>>
>> con.close();
>> }
>>
>>
>> private void sendCmd(IBlockingConnection con, String cmd) throws
>> IOException {
>> LOG.fine("sending " + cmd);
>> con.write(cmd + "\r\n");
>> }
>>
>> private String readResponse(IBlockingConnection con) throws
>> IOException {
>> String response = con.readStringByDelimiter("\r\n");
>> LOG.fine("receiving " + response);
>>
>> return response;
>> }
>>
>> * private String readFileResponse(IBlockingConnection con)
>> throws IOException, BufferUnderflowException,
>> MaxReadSizeExceededException {
>>
>> int length = con.readInt();
>> // the output is:
>> // 24:54:06,359 10 FINE [SimplePicClient#readFileResponse] length:
>> 1164866661
>> LOG.fine("length: " + length);
>> FileChannel fc = new RandomAccessFile(
>> "D:\\1\\tmp.txt", "rw").getChannel();
>> fc.transferTo(0, length, con);
>> fc.close();
>> return "Done";
>> }*
>> }
>>
>> ============== SimplePicServer.java =================
>> package picserver;
>>
>> import java.io.File;
>> import java.io.IOException;
>> import java.io.RandomAccessFile;
>> import java.nio.BufferUnderflowException;
>> import java.nio.channels.FileChannel;
>>
>> import org.xsocket.Execution;
>> import org.xsocket.MaxReadSizeExceededException;
>> import org.xsocket.connection.IConnectHandler;
>> import org.xsocket.connection.IDataHandler;
>> import org.xsocket.connection.INonBlockingConnection;
>> import org.xsocket.connection.IServer;
>> import org.xsocket.connection.Server;
>> import org.xsocket.connection.ConnectionUtils;
>> import org.xsocket.connection.IConnection.FlushMode;
>>
>>
>> public final class SimplePicServer extends Server {
>>
>>
>> public static void main(String[] args) throws Exception {
>> int port = 9527;
>> String outDir = "c://tmp";
>> if (!new File(outDir).exists()) {
>> System.out.println(outDir + " does not exists. creating
>> directory");
>> new File(outDir).mkdirs();
>> }
>>
>> System.out.println("writing mails to directory " + outDir);
>>
>> IServer server = new SimplePicServer(port, outDir);
>> server.setFlushMode(FlushMode.ASYNC);
>> // server.start();
>> ConnectionUtils.registerMBean(server);
>> server.run();
>> }
>>
>>
>> public SimplePicServer(int port, String outDir) throws IOException {
>> super(port, new SimplePicHandler(outDir));
>> }
>>
>> @Execution(Execution.NONTHREADED)
>> private static final class SimplePicHandler
>> implements IConnectHandler, IDataHandler {
>>
>> private String msgFileDir = null;
>> private int countReceivedMessages = 0;
>>
>> public SimplePicHandler(String msgFileDir) {
>> this.msgFileDir = msgFileDir;
>> }
>>
>>
>>
>> public boolean onConnect(INonBlockingConnection connection)
>> throws IOException, BufferUnderflowException,
>> MaxReadSizeExceededException {
>> connection.write("220 ready \r\n");
>>
>> return true;
>> }
>>
>>
>> public boolean onData(INonBlockingConnection connection)
>> throws IOException, BufferUnderflowException,
>> MaxReadSizeExceededException {
>>
>> String cmd =
>> connection.readStringByDelimiter("\r\n").toUpperCase();
>> System.out.println(cmd);
>> if (cmd.startsWith("HELO")) {
>> connection.write("250 Service\r\n");
>> System.out.println("when HELO");
>> } else if(cmd.equals("DATA")) {
>> File msgFile = new File("D:\\1\\mail.txt");
>> connection.setHandler(
>> new DataHandler(msgFile, this));
>> connection.write("Enter message, ending with \".\"\r\n");
>>
>> System.out.println("when DATA");
>>
>> } else if (cmd.startsWith("QUIT")) {
>> connection.write("221 service closing connection\r\n");
>> connection.close();
>> System.out.println("when QUIT");
>>
>> } else {
>> connection.write("500 Unrecognized command\r\n");
>> System.out.println("when else");
>>
>> }
>>
>> return true;
>> }
>>
>>
>> String getMessageFileDirectory() {
>> return msgFileDir;
>> }
>>
>> void setMessageFileDirectory(String msgFileDir) {
>> this.msgFileDir = msgFileDir;
>> }
>>
>> int getCountReceivedMessages() {
>> return countReceivedMessages;
>> }
>>
>> void incCountReceiveMessages() {
>> countReceivedMessages++;
>> }
>> }
>>
>>
>> @Execution(Execution.MULTITHREADED)
>> private static final class DataHandler implements IDataHandler {
>>
>> private SimplePicHandler simplePicHandler;
>> private File file;
>> private FileChannel fc;
>>
>> public DataHandler(File file, SimplePicHandler simplePicHandler) {
>> this.file = file;
>> this.simplePicHandler = simplePicHandler;
>> }
>>
>> * public boolean onData(INonBlockingConnection connection)
>> throws IOException, BufferUnderflowException,
>> MaxReadSizeExceededException {
>>
>> if (fc == null) {
>> fc = new RandomAccessFile(file, "r").getChannel();
>> }
>> int length = (int)fc.size();
>> System.out.println("length: " + length);
>> connection.write(length);
>> connection.transferFrom(fc);
>> fc.close();
>> fc = null;
>> // it's not correct, the handler here failed to go back to
>> SimplePicHandler
>> // the following command are all dealed by DataHandler, which should be
>> dealed by SimplePicHandler.
>> connection.setHandler(simplePicHandler);
>> connection.write("250 OK\r\n");
>> return true;
>> }*
>> }
>>
>> }
>>
>>
>>
>> 2008/11/18 Gregor Roth <gre...@go...>
>>
>> Hi,
>>>
>>> in most cases it is better to use the multithreaded mode (multithreaded
>>> is the default mode). Running the service in a non-threaded mode is a
>>> performance optimization. However, the non-threaded mode will work only
>>> work, if the handler doesn't perform I/O operations such as file or network
>>> operations.
>>>
>>> To avoid outstanding threads while receiving file data, you could read
>>> the network data and write it to a file in a non-blocking mode. For instance
>>> see the Data Handler of the SimpleSmtpServer ->
>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleSmtpServer.java
>>>
>>> To send a file a sync mode has to be used. For instance see the
>>> UploadHandler2 of the SimpleFileChannelPerformanceTest >
>>> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileChannelPerformanceTest.java
>>> With Java 1.7 you will have the option to access the file in an async
>>> mode. In this case you can use a non-blocking, async approach similar to the
>>> file upload scenario.
>>>
>>> If the server reaches the limit by serving many clients, a transport
>>> level load balancing solution will be used to spread the request over a farm
>>> of servers. For a more detailed explanation see link
>>> http://www.javaworld.com/javaworld/jw-10-2008/jw-10-load-balancing-1.html
>>>
>>> Gregor
>>>
>>>
>>>
>>>
>>>
>>> 2008/11/17 beijing welcome <wel...@gm...>
>>>
>>>> hi,
>>>> a discussion for applying xSocket to implement an effective and robust
>>>> file server.
>>>>
>>>> a TCP server stores lots of small pictures (from 1k to 5k for each
>>>> size).
>>>> a client downloads pictures from server frequently, but seldom do
>>>> uploading job.
>>>>
>>>> as far as i know for xSocket, the server can use
>>>> SERVER: transferFrom a FileChannel to BlockingConnection in on
>>>> IDataHandler.onData()
>>>> CLIENT: can use transferTo a FileChannel from BlockingConnection
>>>>
>>>> the communication between client and server has two steps:
>>>> 1. client sends a query to server, server send back the pictures list
>>>> which need to download.
>>>> 2. client begins to download the pictures from server.
>>>>
>>>> if the client need to download more than 10 pictures in a seconds, then
>>>> it seems reasonable to use multi thread.
>>>>
>>>> the question is how to design in server side.
>>>> 1) if use multi thread, how to write the IDataHandler.onData()? if it's
>>>> BlockingConnection, will it block other threads for this connection? if
>>>> NonBlockingConnection, need to write to bytebuffer.duplicate()?
>>>>
>>>> 2) if many clients connect to the same server (e.g. more than 10k), the
>>>> multi thread will rise the connection number? how to minimize the load of
>>>> server? if use proxy to do load balance, any other problem?
>>>>
>>>>
>>>>
>>>> what's your opinion?
>>>>
>>>> any comments are appreciated.
>>>>
>>>>
>>>> -------------------------------------------------------------------------
>>>> This SF.Net email is sponsored by the Moblin Your Move Developer's
>>>> challenge
>>>> Build the coolest Linux based applications with Moblin SDK & win great
>>>> prizes
>>>> Grand prize is a trip for two to an Open Source event anywhere in the
>>>> world
>>>> http://moblin-contest.org/redirect.php?banner_id=100&url=/
>>>> _______________________________________________
>>>> xSocket-develop mailing list
>>>> xSo...@li...
>>>> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
>>>>
>>>>
>>>
>>
> |
|
From: Gregor R. <gre...@go...> - 2008-11-19 07:36:13
|
Hi, I'm not sure if I understand your code. The DataHander is used to send the file to the client. On the other side the DataHandler will be used by handling the data command (which is used to upload data from the client to the server?) I added a simple FileServer into the test trunk of xSocket. See http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServer.javaand http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileServerClient.java May be it helps you to write your server Gregor 2008/11/18 beijing welcome <wel...@gm...> > hi, Gregor, > many thanks for your suggestion, i tried to do. > > the code below were copied from SimpleSmtpClient.java and > SimpleSmtpServer.java, for some reason, it didn't work. > i'm in trouble in the filechannel parts, which were comments in *bold*below. > could you please point me out what's the error? > > > ========== SimplePicClient.java ============ > package picserver; > > import java.io.File; > import java.io.FileInputStream; > import java.io.IOException; > import java.io.RandomAccessFile; > import java.nio.BufferUnderflowException; > import java.nio.channels.FileChannel; > import java.util.logging.ConsoleHandler; > import java.util.logging.Level; > import java.util.logging.Logger; > > > import org.xsocket.LogFormatter; > import org.xsocket.MaxReadSizeExceededException; > import org.xsocket.connection.BlockingConnection; > import org.xsocket.connection.IBlockingConnection; > > > public final class SimplePicClient { > > private static final Logger LOG = > Logger.getLogger(SimplePicClient.class.getName()); > > > private String host = null; > private int port = -1; > > public static void main(String[] args) throws Exception { > > Logger logger = Logger.getLogger(SimplePicClient.class.getName()); > logger.setLevel(Level.FINE); > > ConsoleHandler ch = new ConsoleHandler(); > ch.setLevel(Level.FINE); > ch.setFormatter(new LogFormatter()); > logger.addHandler(ch); > > String host = "127.0.0.1"; > int port = 9527; > > SimplePicClient smtpClient = new SimplePicClient(host, port); > smtpClient.send(); > } > > > > public SimplePicClient(String host, int port) throws IOException { > this.host = host; > this.port = port; > } > > > > public void send() throws IOException { > > IBlockingConnection con = new BlockingConnection(host, port); > > // read greeting > readResponse(con); > > sendCmd(con, "Helo you"); > readResponse(con); > > sendCmd(con, "Data"); > readFileResponse(con); > con.write("\r\n.\r\n"); > > > sendCmd(con, "Quit"); > readResponse(con); > > con.close(); > } > > > private void sendCmd(IBlockingConnection con, String cmd) throws > IOException { > LOG.fine("sending " + cmd); > con.write(cmd + "\r\n"); > } > > private String readResponse(IBlockingConnection con) throws IOException > { > String response = con.readStringByDelimiter("\r\n"); > LOG.fine("receiving " + response); > > return response; > } > > * private String readFileResponse(IBlockingConnection con) > throws IOException, BufferUnderflowException, > MaxReadSizeExceededException { > > int length = con.readInt(); > // the output is: > // 24:54:06,359 10 FINE [SimplePicClient#readFileResponse] length: > 1164866661 > LOG.fine("length: " + length); > FileChannel fc = new RandomAccessFile( > "D:\\1\\tmp.txt", "rw").getChannel(); > fc.transferTo(0, length, con); > fc.close(); > return "Done"; > }* > } > > ============== SimplePicServer.java ================= > package picserver; > > import java.io.File; > import java.io.IOException; > import java.io.RandomAccessFile; > import java.nio.BufferUnderflowException; > import java.nio.channels.FileChannel; > > import org.xsocket.Execution; > import org.xsocket.MaxReadSizeExceededException; > import org.xsocket.connection.IConnectHandler; > import org.xsocket.connection.IDataHandler; > import org.xsocket.connection.INonBlockingConnection; > import org.xsocket.connection.IServer; > import org.xsocket.connection.Server; > import org.xsocket.connection.ConnectionUtils; > import org.xsocket.connection.IConnection.FlushMode; > > > public final class SimplePicServer extends Server { > > > public static void main(String[] args) throws Exception { > int port = 9527; > String outDir = "c://tmp"; > if (!new File(outDir).exists()) { > System.out.println(outDir + " does not exists. creating > directory"); > new File(outDir).mkdirs(); > } > > System.out.println("writing mails to directory " + outDir); > > IServer server = new SimplePicServer(port, outDir); > server.setFlushMode(FlushMode.ASYNC); > // server.start(); > ConnectionUtils.registerMBean(server); > server.run(); > } > > > public SimplePicServer(int port, String outDir) throws IOException { > super(port, new SimplePicHandler(outDir)); > } > > @Execution(Execution.NONTHREADED) > private static final class SimplePicHandler > implements IConnectHandler, IDataHandler { > > private String msgFileDir = null; > private int countReceivedMessages = 0; > > public SimplePicHandler(String msgFileDir) { > this.msgFileDir = msgFileDir; > } > > > > public boolean onConnect(INonBlockingConnection connection) > throws IOException, BufferUnderflowException, > MaxReadSizeExceededException { > connection.write("220 ready \r\n"); > > return true; > } > > > public boolean onData(INonBlockingConnection connection) > throws IOException, BufferUnderflowException, > MaxReadSizeExceededException { > > String cmd = > connection.readStringByDelimiter("\r\n").toUpperCase(); > System.out.println(cmd); > if (cmd.startsWith("HELO")) { > connection.write("250 Service\r\n"); > System.out.println("when HELO"); > } else if(cmd.equals("DATA")) { > File msgFile = new File("D:\\1\\mail.txt"); > connection.setHandler( > new DataHandler(msgFile, this)); > connection.write("Enter message, ending with \".\"\r\n"); > > System.out.println("when DATA"); > > } else if (cmd.startsWith("QUIT")) { > connection.write("221 service closing connection\r\n"); > connection.close(); > System.out.println("when QUIT"); > > } else { > connection.write("500 Unrecognized command\r\n"); > System.out.println("when else"); > > } > > return true; > } > > > String getMessageFileDirectory() { > return msgFileDir; > } > > void setMessageFileDirectory(String msgFileDir) { > this.msgFileDir = msgFileDir; > } > > int getCountReceivedMessages() { > return countReceivedMessages; > } > > void incCountReceiveMessages() { > countReceivedMessages++; > } > } > > > @Execution(Execution.MULTITHREADED) > private static final class DataHandler implements IDataHandler { > > private SimplePicHandler simplePicHandler; > private File file; > private FileChannel fc; > > public DataHandler(File file, SimplePicHandler simplePicHandler) { > this.file = file; > this.simplePicHandler = simplePicHandler; > } > > * public boolean onData(INonBlockingConnection connection) > throws IOException, BufferUnderflowException, > MaxReadSizeExceededException { > > if (fc == null) { > fc = new RandomAccessFile(file, "r").getChannel(); > } > int length = (int)fc.size(); > System.out.println("length: " + length); > connection.write(length); > connection.transferFrom(fc); > fc.close(); > fc = null; > // it's not correct, the handler here failed to go back to SimplePicHandler > // the following command are all dealed by DataHandler, which should be > dealed by SimplePicHandler. > connection.setHandler(simplePicHandler); > connection.write("250 OK\r\n"); > return true; > }* > } > > } > > > > 2008/11/18 Gregor Roth <gre...@go...> > > Hi, >> >> in most cases it is better to use the multithreaded mode (multithreaded is >> the default mode). Running the service in a non-threaded mode is a >> performance optimization. However, the non-threaded mode will work only >> work, if the handler doesn't perform I/O operations such as file or network >> operations. >> >> To avoid outstanding threads while receiving file data, you could read the >> network data and write it to a file in a non-blocking mode. For instance see >> the Data Handler of the SimpleSmtpServer -> >> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleSmtpServer.java >> >> To send a file a sync mode has to be used. For instance see the >> UploadHandler2 of the SimpleFileChannelPerformanceTest > >> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileChannelPerformanceTest.java >> With Java 1.7 you will have the option to access the file in an async >> mode. In this case you can use a non-blocking, async approach similar to the >> file upload scenario. >> >> If the server reaches the limit by serving many clients, a transport level >> load balancing solution will be used to spread the request over a farm of >> servers. For a more detailed explanation see link >> http://www.javaworld.com/javaworld/jw-10-2008/jw-10-load-balancing-1.html >> >> Gregor >> >> >> >> >> >> 2008/11/17 beijing welcome <wel...@gm...> >> >>> hi, >>> a discussion for applying xSocket to implement an effective and robust >>> file server. >>> >>> a TCP server stores lots of small pictures (from 1k to 5k for each size). >>> a client downloads pictures from server frequently, but seldom do >>> uploading job. >>> >>> as far as i know for xSocket, the server can use >>> SERVER: transferFrom a FileChannel to BlockingConnection in on >>> IDataHandler.onData() >>> CLIENT: can use transferTo a FileChannel from BlockingConnection >>> >>> the communication between client and server has two steps: >>> 1. client sends a query to server, server send back the pictures list >>> which need to download. >>> 2. client begins to download the pictures from server. >>> >>> if the client need to download more than 10 pictures in a seconds, then >>> it seems reasonable to use multi thread. >>> >>> the question is how to design in server side. >>> 1) if use multi thread, how to write the IDataHandler.onData()? if it's >>> BlockingConnection, will it block other threads for this connection? if >>> NonBlockingConnection, need to write to bytebuffer.duplicate()? >>> >>> 2) if many clients connect to the same server (e.g. more than 10k), the >>> multi thread will rise the connection number? how to minimize the load of >>> server? if use proxy to do load balance, any other problem? >>> >>> >>> >>> what's your opinion? >>> >>> any comments are appreciated. >>> >>> ------------------------------------------------------------------------- >>> This SF.Net email is sponsored by the Moblin Your Move Developer's >>> challenge >>> Build the coolest Linux based applications with Moblin SDK & win great >>> prizes >>> Grand prize is a trip for two to an Open Source event anywhere in the >>> world >>> http://moblin-contest.org/redirect.php?banner_id=100&url=/ >>> _______________________________________________ >>> xSocket-develop mailing list >>> xSo...@li... >>> https://lists.sourceforge.net/lists/listinfo/xsocket-develop >>> >>> >> > |
|
From: beijing w. <wel...@gm...> - 2008-11-18 17:03:17
|
hi, Gregor,
many thanks for your suggestion, i tried to do.
the code below were copied from SimpleSmtpClient.java and
SimpleSmtpServer.java, for some reason, it didn't work.
i'm in trouble in the filechannel parts, which were comments in *bold*below.
could you please point me out what's the error?
========== SimplePicClient.java ============
package picserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferUnderflowException;
import java.nio.channels.FileChannel;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xsocket.LogFormatter;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.BlockingConnection;
import org.xsocket.connection.IBlockingConnection;
public final class SimplePicClient {
private static final Logger LOG =
Logger.getLogger(SimplePicClient.class.getName());
private String host = null;
private int port = -1;
public static void main(String[] args) throws Exception {
Logger logger = Logger.getLogger(SimplePicClient.class.getName());
logger.setLevel(Level.FINE);
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.FINE);
ch.setFormatter(new LogFormatter());
logger.addHandler(ch);
String host = "127.0.0.1";
int port = 9527;
SimplePicClient smtpClient = new SimplePicClient(host, port);
smtpClient.send();
}
public SimplePicClient(String host, int port) throws IOException {
this.host = host;
this.port = port;
}
public void send() throws IOException {
IBlockingConnection con = new BlockingConnection(host, port);
// read greeting
readResponse(con);
sendCmd(con, "Helo you");
readResponse(con);
sendCmd(con, "Data");
readFileResponse(con);
con.write("\r\n.\r\n");
sendCmd(con, "Quit");
readResponse(con);
con.close();
}
private void sendCmd(IBlockingConnection con, String cmd) throws
IOException {
LOG.fine("sending " + cmd);
con.write(cmd + "\r\n");
}
private String readResponse(IBlockingConnection con) throws IOException
{
String response = con.readStringByDelimiter("\r\n");
LOG.fine("receiving " + response);
return response;
}
* private String readFileResponse(IBlockingConnection con)
throws IOException, BufferUnderflowException,
MaxReadSizeExceededException {
int length = con.readInt();
// the output is:
// 24:54:06,359 10 FINE [SimplePicClient#readFileResponse] length:
1164866661
LOG.fine("length: " + length);
FileChannel fc = new RandomAccessFile(
"D:\\1\\tmp.txt", "rw").getChannel();
fc.transferTo(0, length, con);
fc.close();
return "Done";
}*
}
============== SimplePicServer.java =================
package picserver;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferUnderflowException;
import java.nio.channels.FileChannel;
import org.xsocket.Execution;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;
import org.xsocket.connection.ConnectionUtils;
import org.xsocket.connection.IConnection.FlushMode;
public final class SimplePicServer extends Server {
public static void main(String[] args) throws Exception {
int port = 9527;
String outDir = "c://tmp";
if (!new File(outDir).exists()) {
System.out.println(outDir + " does not exists. creating
directory");
new File(outDir).mkdirs();
}
System.out.println("writing mails to directory " + outDir);
IServer server = new SimplePicServer(port, outDir);
server.setFlushMode(FlushMode.ASYNC);
// server.start();
ConnectionUtils.registerMBean(server);
server.run();
}
public SimplePicServer(int port, String outDir) throws IOException {
super(port, new SimplePicHandler(outDir));
}
@Execution(Execution.NONTHREADED)
private static final class SimplePicHandler
implements IConnectHandler, IDataHandler {
private String msgFileDir = null;
private int countReceivedMessages = 0;
public SimplePicHandler(String msgFileDir) {
this.msgFileDir = msgFileDir;
}
public boolean onConnect(INonBlockingConnection connection)
throws IOException, BufferUnderflowException,
MaxReadSizeExceededException {
connection.write("220 ready \r\n");
return true;
}
public boolean onData(INonBlockingConnection connection)
throws IOException, BufferUnderflowException,
MaxReadSizeExceededException {
String cmd =
connection.readStringByDelimiter("\r\n").toUpperCase();
System.out.println(cmd);
if (cmd.startsWith("HELO")) {
connection.write("250 Service\r\n");
System.out.println("when HELO");
} else if(cmd.equals("DATA")) {
File msgFile = new File("D:\\1\\mail.txt");
connection.setHandler(
new DataHandler(msgFile, this));
connection.write("Enter message, ending with \".\"\r\n");
System.out.println("when DATA");
} else if (cmd.startsWith("QUIT")) {
connection.write("221 service closing connection\r\n");
connection.close();
System.out.println("when QUIT");
} else {
connection.write("500 Unrecognized command\r\n");
System.out.println("when else");
}
return true;
}
String getMessageFileDirectory() {
return msgFileDir;
}
void setMessageFileDirectory(String msgFileDir) {
this.msgFileDir = msgFileDir;
}
int getCountReceivedMessages() {
return countReceivedMessages;
}
void incCountReceiveMessages() {
countReceivedMessages++;
}
}
@Execution(Execution.MULTITHREADED)
private static final class DataHandler implements IDataHandler {
private SimplePicHandler simplePicHandler;
private File file;
private FileChannel fc;
public DataHandler(File file, SimplePicHandler simplePicHandler) {
this.file = file;
this.simplePicHandler = simplePicHandler;
}
* public boolean onData(INonBlockingConnection connection)
throws IOException, BufferUnderflowException,
MaxReadSizeExceededException {
if (fc == null) {
fc = new RandomAccessFile(file, "r").getChannel();
}
int length = (int)fc.size();
System.out.println("length: " + length);
connection.write(length);
connection.transferFrom(fc);
fc.close();
fc = null;
// it's not correct, the handler here failed to go back to SimplePicHandler
// the following command are all dealed by DataHandler, which should be
dealed by SimplePicHandler.
connection.setHandler(simplePicHandler);
connection.write("250 OK\r\n");
return true;
}*
}
}
2008/11/18 Gregor Roth <gre...@go...>
> Hi,
>
> in most cases it is better to use the multithreaded mode (multithreaded is
> the default mode). Running the service in a non-threaded mode is a
> performance optimization. However, the non-threaded mode will work only
> work, if the handler doesn't perform I/O operations such as file or network
> operations.
>
> To avoid outstanding threads while receiving file data, you could read the
> network data and write it to a file in a non-blocking mode. For instance see
> the Data Handler of the SimpleSmtpServer ->
> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleSmtpServer.java
>
> To send a file a sync mode has to be used. For instance see the
> UploadHandler2 of the SimpleFileChannelPerformanceTest >
> http://xsocket.svn.sourceforge.net/viewvc/xsocket/xsocket/core/trunk/src/test/java/org/xsocket/connection/SimpleFileChannelPerformanceTest.java
> With Java 1.7 you will have the option to access the file in an async mode.
> In this case you can use a non-blocking, async approach similar to the file
> upload scenario.
>
> If the server reaches the limit by serving many clients, a transport level
> load balancing solution will be used to spread the request over a farm of
> servers. For a more detailed explanation see link
> http://www.javaworld.com/javaworld/jw-10-2008/jw-10-load-balancing-1.html
>
> Gregor
>
>
>
>
>
> 2008/11/17 beijing welcome <wel...@gm...>
>
>> hi,
>> a discussion for applying xSocket to implement an effective and robust
>> file server.
>>
>> a TCP server stores lots of small pictures (from 1k to 5k for each size).
>> a client downloads pictures from server frequently, but seldom do
>> uploading job.
>>
>> as far as i know for xSocket, the server can use
>> SERVER: transferFrom a FileChannel to BlockingConnection in on
>> IDataHandler.onData()
>> CLIENT: can use transferTo a FileChannel from BlockingConnection
>>
>> the communication between client and server has two steps:
>> 1. client sends a query to server, server send back the pictures list
>> which need to download.
>> 2. client begins to download the pictures from server.
>>
>> if the client need to download more than 10 pictures in a seconds, then it
>> seems reasonable to use multi thread.
>>
>> the question is how to design in server side.
>> 1) if use multi thread, how to write the IDataHandler.onData()? if it's
>> BlockingConnection, will it block other threads for this connection? if
>> NonBlockingConnection, need to write to bytebuffer.duplicate()?
>>
>> 2) if many clients connect to the same server (e.g. more than 10k), the
>> multi thread will rise the connection number? how to minimize the load of
>> server? if use proxy to do load balance, any other problem?
>>
>>
>>
>> what's your opinion?
>>
>> any comments are appreciated.
>>
>> -------------------------------------------------------------------------
>> This SF.Net email is sponsored by the Moblin Your Move Developer's
>> challenge
>> Build the coolest Linux based applications with Moblin SDK & win great
>> prizes
>> Grand prize is a trip for two to an Open Source event anywhere in the
>> world
>> http://moblin-contest.org/redirect.php?banner_id=100&url=/
>> _______________________________________________
>> xSocket-develop mailing list
>> xSo...@li...
>> https://lists.sourceforge.net/lists/listinfo/xsocket-develop
>>
>>
> |
|
From: Gregor R. <gre...@go...> - 2008-11-18 16:25:28
|
Hi Jimmy, the NonBlockingConnection as well as the BlockingConnection support´s marking. You can set a read mark, read data, and reset the read position the marked position. Do you know this feature? For a more detailed explanation see tutorial chapter 15. The next version of xSocket will support a isServerSide() method Gregor 2008/11/18 yanping gao <yan...@gm...> > hi Gregor: > > When I try to implement my NIO Server, I found some little feature is > lack: > > 1. in xsocket, now support get by lenght and get by delimiter, is most > case, it is OK; but some times, I cannot > get the packet's length or delimiter before decoding; so I need try > decode and valide checksum; in this case, need > pushback stream, maybe unread(...) is preferable. > > 2. INonBlockingConnection is both client and server connection, if I > could know the connection is which side, it will help > for processing, maybe need isServerSide() in connection. > > -- > Jimmy Gao > Software Senior Product Manager > yan...@gm... > > ------------------------------------------------------------------------- > This SF.Net email is sponsored by the Moblin Your Move Developer's > challenge > Build the coolest Linux based applications with Moblin SDK & win great > prizes > Grand prize is a trip for two to an Open Source event anywhere in the world > http://moblin-contest.org/redirect.php?banner_id=100&url=/ > _______________________________________________ > xSocket-develop mailing list > xSo...@li... > https://lists.sourceforge.net/lists/listinfo/xsocket-develop > > |