Multi-threaded server programming

Hello, I meet a problem and don't know how to solve it: I have created a multi-threaded server program which receives multiple users from their own PCs. The server program receives users'commands and echo it back to all users who are currently connecting to my server. I store every clientSocket connecting to my server into a vector. My question is: how the server broadcasts a user command to other users? And how the server knows to which user he will echo the command to since the hostName and port number are the same to every user currently connecting to my server? Thanks a lot.

You should look at extending the Socket class to encorporate user details. Either use what peter suggested or make the user pass a username (or something) when they connect.
When you want to broadcast to all users just enumerate through your vector and send each one the command. If you mean the user performs a task on their application and you want to produce the same results in all the other users apps then its down to you to code it. When user1 clicks on a button the app must send a command (eg. a string) to the server which sends the same string to all other users. When the user receives this string it performs some task.
Is that what you mean?
Ted.

Similar Messages

  • Multi-threaded server with independent IO

    I have designed a multi-threaded server which handles XML via sockets. I am running into the issue that when I try to send data to all of the clients, I have having to iterate through a shared resource where the sockets are stored at. I do not have this problem with reading because it is done in the thread created for this client (I pass the socket into the thread). If one computer freezes, then the iteration (writeToAll) through the client sockets also freeze. I would like to send XML to all clients and have everything fully independent so if it has a problem writing to a client, then it wouldn't halt the server. I would spawn a new thread for each write but that wouldn't be practical and I worry about threads live-locked.
    I have looked into JCSP and it looks promising for the common issues associated with thread programming, but this is more of a design issue.
    Any robust multi-threaded servers out there for enterprise use and scalability?

    A basic server which provides an example of what I mean:
    http://www.wellho.net/solutions/java-a-multithreaded-server-in-java.html
    connectiontable is a non-synchronized static method; I use a synchronized non-static method. I do not know which one I need to use.
    The problem: If a socket "lingers" on sending output* (ex if the client is frozen but the socket is still bounded), then it never throws an exception!
    *Sending from a shared resource (hashtable) on the parent thread (where the serversocket resides).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Multi Thread Server over TCP/IP

    Multi Thread Server over TCP/IP. Does it work?
    In my box it works only over IPC protocol.
    null

    S C Maturi (guest) wrote:
    : Mark Malakanov (guest) wrote:
    : : Multi Thread Server over TCP/IP. Does it work?
    : : In my box it works only over IPC protocol.
    : Mark,
    : Multi threaded server over TCP/IP will not work with
    : the current distribution of Oracle 8.0.5 on Linux.
    : This is corrected and a patch would be released soon.
    : Maturi
    tcp 0 0 bock.nettek-ll:listener bock.nettek-
    llc.co:4196 ESTABLISHED
    tcp 0 0 bock.nettek-llc.co:4196 bock.nettek-
    ll:listener ESTABLISHED
    (I have serveral of these)
    TNS Ping Utility for Linux: Version 8.0.5.0.0 - Production on 07-
    JAN-99 18:45:52
    (c) Copyright 1997 Oracle Corporation. All rights reserved.
    Attempting to contact (ADDRESS=(PROTOCOL=TCP)(HOST=localhost)
    (PORT=1521))
    OK (440 msec)
    ...and from my install log you see that I selected MTS:
    -[ YESNO
    Q> Would you like MTS (Multi-Threaded Server) configured
    and the SQL*Net$
    A> TRUE
    Please explain? Will TCP/IP MTS work via the loopback adapter
    only? So far I have not tried a remote TCP/IP connection.
    -STEVEl
    null

  • Enterprise User and Multi Thread Server

    Hi,
    We are going to build a system which uses a configuration:
    10g2
    Enterprise User
    Multi Thread Server
    Client apps accesses db over JDBC/SSL
    Could some please share experience about issues regarding
    using Enterprise User and Multi Thread Server ?
    Is MTS transparant for Enterprise User authentication ?
    Regards,
    Cezary

    If you build simpserv with -t, and set MIN and MAXDISPATCHTHREADS, you
    should have an example of a multithreaded server.
         Scott
    Johan Philippe wrote:
    >
    We have been going to the documentation on multi-threading and contexting in servers
    on Tuxedo 7.1.
    And the impression so far is that apart from the function definitions there is
    not much information around.
    Didn't even find a simple example of a multi-threaded server in the Bea refs yet.
    Does anyone know/have such an example?
    And is anyone using multi-contexting in a server, because the limitation that
    only server-dispatched
    thread get a context puts quite a limitation on its usefullness.

  • Found dead multi-threaded server

    hi all
    My database is not running in multithread mode.
    mts_dispatchers = "(protocol=TCP)"
    I am getting such error
    found dead multi-threaded server 'S000', pid = (8, 4)
    Pl guide me
    suresh

    go on metalink http://metalink.oracle.com
    Good Luck,
    Fred

  • Found Dead Multi-Threaded Server Error!!!

    I am in the process of testing an application based on EJBs deployed on an Oracle 8.1.5 database.
    Some times the whole instance chashes without any obvious reason.
    The error reported in the Alert file is
    "found dead multi-threaded server 'SOOO',pid(8,1). Terminating Instance".
    I check my code and i think that there is no problem with cleaning up resources. I increased also the JAVA_POOL_SIZE and LARGE_POOL_SIZE size without any result.
    Can anybody give me a hint for the error cause?
    Thanks in advance.
    null

    go on metalink http://metalink.oracle.com
    Good Luck,
    Fred

  • Dedicated server vs multi threaded server archcitechture ( shared servers)

    http://www.dba-oracle.com/t_mts_multithreaded_servers_shared.htm
    1. I read the above for dedicated server vs multi threaded server archcitechture ( shared servers), please make it easy for a novice like me to understand in brief. Is the difference between the two only that MTS spawn multiple virtual servers which share and same memor ?
    2. How does the dedicated server work right from a db user logs in to when the user logs out ?
    Thanks in advance.
    Gony

    Posting it in [General Forum|http://forums.oracle.com/forums/forum.jspa?forumID=61] is more appropriate.
    SS

  • Can anybody know how to configure Multi threaded server?

    Hi
    All,
    Can anybody know how to configure Multi threaded server?
    Thanks,
    Vishal

    Values are just samples only. use what ever appropriate for your environment. Understand each of them before using in production.
    alter system set DISPATCHERS="(PROTOCOL=tcp)(DISPATCHERS=3)(CONNECTIONS=1000)"
    alter system set shared_servers=100
    replace "DEDICATED" with "SHARED" in tns names
    Ready to go.
    select username,server from gv$session (server should show none or shared)

  • Multi-Threaded server using  ThreadPool

    Dear friends,
    I am writing a client-server program in which the client and server communicate using SUN-RPC. The client reads a file containing some numbers and then spawns threads which it uses to request the server for a service. These threads are executed using a thread pool. Till this time, it's working fine. But when it comes to the server, the real trouble begins because it too needs to be made a multi-threaded one using thread pooling. The server has to capture the call information for each request for the service and then pass this information to a thread/runnable object in whose run() method the code for execution of the service would be present. Since the tasks(requests for the service) are not present already, i am unable to execute the server side threads in a loop using a thread pool. How to solve this problem? Kindly help.
    Thanks,
    Subhash

    The server has to capture the call information for each request for the serviceWhy?
    and then pass this information to a thread/runnable object in whose run() method the code for execution of the service would be present.Why can't the run() method get the call information when it starts? That's what's normally done. The server's accept loop mustn't do any other I/O: otherwise a rogue client can block the server complete.y

  • SAP XI on a multi-core, multi-thread server?

    Hi Everyone!
    Can anyone tell me whether SAP XI can run on a Server whose processor is multi-core, multi thread (4 cores, 8 threads per core, 32 threads)?
    Thanks in advance!
    Warm regards,
    Glenn

    Hi Ravi,
    Thanks for your reply! The server in question is SUN Solaris. What sort of confguration needs to be done on both the OS side and on XI? Is there a SAP note I can follow?
    Warm regards,
    Glenn

  • Writing a multi-threaded server

    Hi. I'm working in a starting project here at my company and, as a requirement, I must implement a multithreaded server using SSL connections (SSL over Socket). The secure connection is no longer a concern (after a lot of struggle, I build a simple client/server over SSLSockets that actually works), but I still need to build all the multithreaded code... I'm needing some guidelines and design ideas. Any ideas? Can someone post some interesting links about this subject?
    Thanks in advance!

    >
    For example why must it be multi-threaded in thefirst
    place?Because it will serve a few tens of people
    concurrently.
    tens? Like 50 people or 500 people?
    And how many threads? 3 or 60,000?I do not know yet, but I'm assuming it will be one
    thread per socket connection and possibly another few
    threads doing housekeeping stuff (managing files,
    etc)
    And how long will a thread last? What sort of
    processing will it do?Ain't got all requirements yet!! But basically (at
    least what I understood) it's going to receive lots of
    data, process it and re-route the data to a mainframe
    So 5O (or 500) people are going to connect...
    1. Once a week and deliver 10 giga bytes of data?
    2. Once a minute and deliber 10 giga bytes of data?
    3. Once a week and deliver 1,000 bytes of data?
    4. Once a minute and deliber 1,000 bytes of data?
    And then the general questions for any 'server'...
    -What happens when the server (box or application)fails
    Well, nothing has been said about that matter yet, but
    I guess the server got to resume (or discard)
    unfinished stuff (depending on the status of the
    received data before the connection was lost)
    And how is it going to do that on the 'mainframe'?
    Two easy paths.
    1. The mainframe has a database interface AND the data volume is low enough then you can use transactions.
    2. The data does not have to be committed at once. This could be because it just doesn't always need to go, or because it is 'sequential' (which still requires code but not much.)
    Really hard paths.
    1. 'Lots' of data and it all must be committed at 'once'.
    2. There is no database interface and data must be committed.
    -What is the expected scaling requirements?No clustering involved - it will run on a single
    machine, during a limited time. The system in question
    is a 'contingency control' (not sure about this term
    in English), so it will run when (and if) our client
    get screwed in any way - their buildings destroyed,
    that kind of stuff...
    -How will it be maintained?Sorry, I didn't understood, could you clarify?
    Someone has to make sure the box and application is running. Who is going to do that? What tools will they need to do this?
    If it is you and the users call you directly if it doesn't work then it is easy (code wise.) If it is someone else then you will need to provide tools to ease that. And if someone expects it to work in an automated management system (like with SNMP) it is going to be even more complicated.

  • Multi-thread server with UD32

    Hi
    I have build server with -t for muli-thrread option, it boots fine too. When I
    use UD32 < file. ud it does not work.
    I get following error in ULOG.
    103708.gdev!ProxSvr.26508.4.1: LIBTUX_CAT:6126: INFO: New server dispatched thread
    starting
    103708.gdev!ProxSvr.26508.1.-2: LIBTUX_CAT:476: WARN: Server 3/511: client process
    26500: lost message
    103708.gdev!ProxSvr.26508.1.-2: LIBTUX_CAT:477: WARN: SERVICE=PROXSVC MSG_ID=0
    REASON=server died
    It work when server is not build with -t option.
    Any help ?
    Vijay

    Here's a huge list of SOAP servers:
    http://www.soapware.org/directory/4/implementations
    Here's a SOAP/RMI product called XSOAP that might make more sense for you.
    http://www.extreme.indiana.edu/xgws/xsoap/

  • Application Server Configuration with Multi-threaded Server

    Hi, friends:
    We seems to have some problem with our OAS configuration. Even our Oracle8 server is set as MTS, when we query through the OAS, everytime one request won't be processed until the previous one finished. How to configure OAS to process queries in parellel?
    Also, is there anyway that we can cancel a running query? Because, usually our query is very time-consuming. But even we stopped it apparently in the interface end, we know it is still running backend. Performance is bad.
    Thank you, Thank you.
    David

    Hi Balaji,
    The Application server step by step guide is in the same guide as the CI installation guide. If you don't have it already you can download it from SAP Marketplace.
    Regards
    Juan

  • Multi threaded Server

    Hi all,
    I am not a DBA and don't have DBA acces on my production server. Please let me know how to identify,MTS is enabled on my server or not?
    Also I found this in statspack report
    session pga memory                     7,211,525,400       46,291.5        652.5
    session pga memory max                 9,380,680,064       60,215.6        848.7
    session uga memory                 2,779,758,410,912   17,843,556.3    251,495.4
    session uga memory max                21,093,800,328      135,403.3      1,908.4Can I say 'Session UGA Memory' is high because shared server is used by these sessions?
    Also If MTS is enabled/installed and if I don't give server=dedicated or server=shared in my tnsnames, then that session would use shared connection or dedicated connection?
    I am using oracle 9i rel2
    Thanks in advance,
    Jaggyam

    Hi,
    I am not a DBA and don't have DBA acces on my production server. Please let me know how to identify,MTS is enabled on my server or not?If you can check the init parameter by querying v$parameter then check value for shared_servers, dispatchers. They should be greater than 0
    Can I say 'Session UGA Memory' is high because shared server is used by these sessions?No you cannot.
    Also If MTS is enabled/installed and if I don't give server=dedicated or server=shared in my tnsnames, then that session would use shared connection or dedicated connection? It should use shared connection if possible like availability of dispatchers etc. If it is not possible to connect through shared server then it uses dedicated server.
    Regards
    Anurag Tibrewal

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

Maybe you are looking for

  • Invalid Username and password ....while login in workspace

    error"you must supply a valid user name and password to log on the system." I have provisioned properly in shared services and also configured web server ..but while trying to login in workspace,getting error"you must supply a valid user name and pas

  • How to connect external display to iMac

    which port do I use to connect external display to my iMac ?

  • Regarding Vendor Master Control settings

    Hi . Can somebody expain Vendor master settings and what all they control ? Also, who is considered as Second Vendor? Thansk & Regards, Smitha

  • Getting data from 3 tables

    Hi all, Iam working with a jdbc-to-jdbc scenario.In this I am having 3 tables on source side called t1 , t2 & t3. On target side I am having 2 tables called tb1 & tb2. Now I have to retrieve data from 3 tables and insert into 2 tables using one type

  • Help !! help !! mysql bc4j and jheadstart & uix

    hi please help me i make a bc4j project against mysql database server i used jdbc connection with the wy as described in the document :How To Use ADF Business Components with MySQL url:http://www.oracle.com/technology/products/jdev/howtos/10g/MySql/M