Question, in a client server implemention

Question, in a client server implemention using only basic sockets and datagrams, what happens if a method is being called at the server side while the same method is already being called/running for another client?
Example:
Client 1 calls Method 1 at Server Side. Method 1 runs.
Client 2 calls Method 1 at Server Side. Method 1 is still running for Client 1. Does it create another Thread and runs for Client 2? Or do I have to implement a seperate Thread for each Client myself?

Thanks!
Don't want to start a new thread so might as well ask this here,
Is there a way to pass or at least update the value of a variable from the outside into a Thread that is running? And this value needs to be seen and be the same for all Threads.
I am thinking of creating new a class that to hold the value I want to update, and passing an object of the class in to the Threads before they runs. Since objects hold reference to the location of the actual object or something like that; people always get worked up over this if I phrase this incorrectly, but I think I got the point across, so that's okay. If I change the value of the object at runtime in the main method, like assign it with a new value according to user input. All the Threads will get the new value right?
Something like that.
public class valueToUpdate {
String value;
public valueToUpdate(String value) {
this.value = value;
public String getValue() {  
return value;  
public class Main {  
public static void main(String[] args) {  
String str = "abc";  
valueToUpdate vTU = new valueToUpdate(str);  
ThreadClass tc1 = new ThreadClass(vTU);  
Thread thread1 = new Thread(tc1).start();  
ThreadClass tc2 = new ThreadClass(vTU);  
Thread thread2 = new Thread(tc2).start();   
public class ThreadClass implements Runnable {  
valueToUpdate vTU;  
public ThreadClass(valueToUpdate vTU) {  
this.valueToUpdate = valueToUpdate;  
public void run() {  
System.out.println(valueToUpdate.getValue());  
}Okay, something like that. I know I need to add in a TimerTask for ThreadClass too for it to run for a certain period. But if I were to ask for user input at the main method while the TimerTask in running, and I change the value of vTU, will the output for both Threads be changed to the value of the user input?
Or is there a better way to do it?

Similar Messages

  • JMS architecture question for fat client/server.

    Hi. Is JMS suitable for fat client-server architecture where a certain number of fat client applications (like a few hundreds) open connections directly to the JMS provider? Is it going to have scalability problem when the number of connections grow?

    Depending on your JMS provider, this may be a very suitable architecture. The Sun MQ JMS Cluster was architected exactly for this problem. If the number of connections onto a single broker becomes too much of a burden for this broker, it can be put into an MQ cluster and share the number of connections. Of course, the number of connections a broker can handle will be totally dependent on the resources available to it. OS, CPU, memory, other applications running on the same machine, etc....
    TE

  • Sockets question (multiple user, client-server application)

    I'm new to sockets and I think I've been designing my application all wrong.
    I've been using the KKMultiServer example from this website. It creates new threads using the Socket.accept() function. However, all the clients connect to the same port on the server.
    What I'm creating is a multi-user TicTacToe program. So far it's only for two players, but I would like to create a game "lobby" where lots of users can connect and play games with each other.
    Do I need to specifcy local ports for the clients that are connecting? Should I be using different ports on the server for each user so the traffic doesn't get mixed up?

    a socket is made up of 4 elements.
    1) the server or host IP address
    2) the server port
    3) the client IP address
    4) the client port
    for a socket to be unqiue one of these elements must be different.
    to make these unique client sockets use a port assigned by the OS and so you can have more than one client connected to a server and 1 client machine can have more than 1 open socket.
    here is a print out from netstat (an IP utility on windows that shows some of my open sockets...
    Active Connections
    Proto Local Address Foreign Address State
    TCP CHEF2:1033 CHEF2:3306 ESTABLISHED
    TCP CHEF2:3306 CHEF2:1033 ESTABLISHED
    TCP CHEF2:3306 CHEF2:3626 ESTABLISHED
    TCP CHEF2:3306 CHEF2:3743 ESTABLISHED
    TCP CHEF2:3626 CHEF2:3306 ESTABLISHED
    TCP CHEF2:3743 CHEF2:3306 ESTABLISHED
    TCP CHEF2:1278 216.71.131.122:22 ESTABLISHED
    TCP CHEF2:1694 kw40.primenetwork.net:http CLOSE_WAIT
    TCP CHEF2:1863 67.72.120.62:http CLOSE_WAIT
    TCP CHEF2:1869 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:1870 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:1871 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:1872 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:1875 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:1881 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:1884 host16.ipowerweb.com:http TIME_WAIT
    TCP CHEF2:3623 216.71.131.122:ftp CLOSE_WAIT
    TCP CHEF2:3841 CARTMAN:netbios-ssn ESTABLISHED
    at any rate
    notice how on my machine (CHEF2) i have a service running on port 3306. i also have three sockets open from my machine acting as a client to the service. you can see it lists these three open sockets to my machine twice each.
    at any rate it can tell them all apart from the server end because the port used by the client is different.
    to sum up this and the answer given above you don't have to worry about it.

  • Client Server mode for time ten connection

    Hi, I am new to Times Ten and got a question for running TimesTen in Client Server Mode. When it is running in Client/Server mode:
    Does the database just run like a regular remote database ?
    Is there security for the remote application, such as userid/password ?
    Is there any limitation on number of remote connection can concurrently connect to the DB ?
    Does it use the JDBC or it has to be the native library ?
    Thank you for your help
    Henry

    Hi,
    With regard to your questions regarding TimesTen client/server mode:
    1. Does the database just run like a regular remote database ?
    I'm not sure exactly what you are getting at here but yes, I would say that it runs like any other c/s database. If you can be more specific in your question then I can give a more precise answer.
    2. Is there security for the remote application, such as userid/password ?
    If the TimesTen instance to which you are connecting was installed with Access Control enabled then yes, normal userid/password security applies. The client application must provide a valid TimesTen userid and password in order to establish a connection.
    3. Is there any limitation on number of remote connection can concurrently connect to the DB ?
    Subject to O/S resource limitations, a single instance of TimesTen (i.e. the TT server) supports a maximum of 9,999 concurrent client/server connections. Each individual datastore supports a maximum of 2047 concurrent connections (direct and client/server).
    4. Does it use the JDBC or it has to be the native library ?
    The TimesTen JDBC driver supports both direct modde and client/server. The TimesTen ODBC driver is provided in both direct mode and client/server versions. The JDBC driver uses the ODBC driver (it is a type 2 JDBC driver) and so the client machine requires a TimesTen client installation to use either ODBC or JDBC to access a remote datastore.
    Chris

  • Client/Server application question

    Hey everyone,
    I am trying to exercise on a client/server application. My client application is similar to this one [http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/Code/SocketClient.java]. However this client works like this: it sends text through socket -> receive response from server. I am trying to find a way so that the client can receive and process messages from the server asynchronously. That is the server can send messages anytime (not just as a response to the client) and the client should always be able to receive messages from the served at any time, and not just after it sent something. I believe that multithreading would be the answer, listening to the output stream and sending through the input stream should be run in parallel, but I can't find a way to implement it. Your help is appreciated. Thank you.

    I knew that :-) but how exactly?
    How do I translate this code into two runnable classes which will communicate with the original class and its gui?
    //Send data over socket
              String text = textField.getText();
              out.println(text);
           textField.setText(new String(""));
    //Receive text from server
           try{
           String line = in.readLine();
              System.out.println("Text received :" + line);
           } catch (IOException e){
          System.out.println("Read failed");
                 System.exit(1);
      }

  • Forms 6i client/server questions

    Hi, I have three questions:
    1) Is Patch 17 for Forms6i cumulative? (we have patched up to patch 13)
    2) After applying patch 17 do we need to recompile all of our forms?
    3) We are connecting from 6i client/server forms to a 10.1.4 database, is there a recommended Oracle client? (we are very behind and still running a very old version and I'm trying to get information to move forward)
    Thanks.

    Patch 17 is designed for the 10g database. There is no hint, that a 9i-db is better than a 10g. Use 10g.
    I always recompile all (!) libs, menues and forms after installing a new patch. It's better to do that once, than to search for failures, that result from patching.
    try it
    Gerd

  • How long is it to implement JSSE on a client-server architecture?

    Hi all of you,
    Since I'm not a developper but more a system admin, I'm wondering how long approximatly it would take to adapt an existing JAVA client-server architecture to use JSSE or SSL communication over the internet. Is it a simple task or are we talking about weeks of work? Where would be installed the SSL certificate, on the web server or the database server? In brief, what are the main steps that a developper has to go through?
    Architecture:
    JAVA client
    Web server (RMI server), Microsoft IIS5.0
    Database server (MySQL4.0)
    Thanks you all for your precious time,
    AD

    If your webserver has a server certificate from one of the "Big Boys" in the CA business, and if you don't need client-authentication (and almost no-one does) - in your client, write "SSL" in front of everywhere the app currently has the word "Socket", and scratch out "HttpUrl" and replace it with HttpsUrl,." and change your access-urls to start with "https:" and change your socket-connections to talk to your server's SSL port, and you're done. I've taken a Socket-based app and made it SSL/Plain bilingual in two hours once (admittedly, it was a small and well-designed app).
    If your server-cert isn't signed by a known CA, then you have to play some games to get the client side to accept it - but they've all been discussed to death in this forum.
    Grant

  • Client server applet question

    Hello I have a client and server program on computer a and computer b.
    I want a webpage with a java applet.
    I want that if I push a button in the client the java applet gets a message.
    I want that the server looks for changes in the applet and when there is a change the server does something.
    I have a program where the client and server communicate with eachother but how can I make a program like I want?
    How can I send a message to the applet(on a webpage) from the client and how can I look at the applet with my server??

    Aplet runs on client side (in other words on PC which is used to view page). On server side it is stored only as any other kind of file. To be able to create "client-server" solution you have to be able to run code also on server machine. I did not found any free hosting server which allows to run java. But in many cases they allow to use PHP which runs enteirly on server side. Check for this - it may be right solution for you.

  • Need Help for client - server - client question [Sockets]

    Hi
    I have read the http://java.sun.com/docs/books/tutorial/networking/sockets/index.html tutorial and made this Knock Knock Application.
    But now, I want that one client can view all the other clients which are connected to the server, and interract with a selected cleint over the server (client - server - client).
    But I have no idea how to build such a registration concept?
    A concrete hint (or link) how to realise this would be very helpful. I searched all the internet for examples, but I dont found a simple example.
    Thanks in advance
    greeds

    wSam,
    It appears that Sun considers RMI to be simpler, although less efficient than the alternative:
    http://java.sun.com/developer/technicalArticles/ALT/sockets/
    This article also talks about object serialization, which I am a fan of. Suppose that you want to send a data structure containing lots of information (like all connected users). You can actually pass an object (rather than text) across the network using ObjectOutputStream and receive it on the other end with ObjectInputStream. You might create your own Command class for passing objects between the client and server instead of using RMI. The Command class might hold flags that indicate which method should take place on the remote machine (i.e. send chess move command).

  • Client/server vs. Application Server

    Our company has around 30 sites with each one having its own Oracle database server and file server (repository for executables of Forms6i/Reports6i). All the sites have the same applications running, i.e., the same set of programs are replicated to each site. At present we are running the applications in client/server mode (Forms6i/Reports6i runtime is installed on each client machine).
    We are also using some third party modules developed in VB/VC++.
    Now we are looking for the Centralized Solution, i.e., We want to have a Single Database Server available to all the sites all the sites are already linked with Network Leased lines).
    Now we want to know the impact of running centralized file server (located at Corporate Office site) accessible from all the sites (through same client/server mode).
    Will this solution work for us or we should move to 3-tier mode? Please suggest us the best feasible solution which can be implemented as early as possible.
    What I mean to ask in the question above is: if a good intranet connectivity is available among sites, what would be the better approach, client/server or n-tier?
    What actually would we gain by using application server in this context? Does the Data travelling is reduced from Database Server through to the Client Node in 3-tier AS approach? Does this 3-tier approach will reduce the Burden on Leased Lines? Does we gain more network resources available in 3-tier?
    What I think is that in client/server mode, the data is travelled from Database Server to Client Machine, but using Application Server, the Data from Database Server will travel upto Application Server and NOT to the Cleint machine (on browser etc.), hence reducing Network Load.
    Please clarify as your input makes a valuable role in our decision-making.

    Hello,
    I'll take a stab at this one...
    If you have enough network bandwidth, you should be fine funning in client/server mode. I have worked with clients with this same configuration. In addition to having a centralized DB, we have also centralized the forms on a network drive allowing users to access the same files and removing the need for users having to update their files locally. The biggest problem I see with this configuration, as long as you have enough band width, is that your configuration is not supported as 6i has been desupported.
    From my perspective you really don't have any choice but to upgrade your application so that you can be supported. The good news is that for the clients we have worked with upgrades have gone very smoothly. In fact recently we have started to partner with another vendor that has a tool specifically designed to upgrade Oracle Forms and it includes additional features above and beyond what you get from Oracle. This tool has drastically reduced the amount of time to complete upgrades (like going from a 2 year project to just a few weeks).
    I hate to answer this question because it is hard to answer without really getting into the details with you. The good news is once you do have a centralized DB and centralized application maintenance will be significantly easier.
    One last option you might consider that our company has done is to use Citrix. I've never used it for Oracle Forms, but for other client/server applications it has allowed out clients to web enabled their existing applications without changing them at all and also get a boost in performance. I wouldn't recommend this approach to you because what you have should be short term until you get your forms/reports upgraded.
    If you have any specific questions I can try and answer them for you. Good luck and let me know if I can be of any assistance.

  • FRM-40735 on the Web, in client/server without error

    We have 2 types of Form modules.
    Type 1 are simple multirecord modules,
    which uses PL/SQL library module PL1.plx.
    Type 2 are complex (master-detail) modules,
    which uses PL/SQL library module PL2.plx.
    In client/server, both types of Form modules work fine.
    On the Web (Intranet), type 1 modules works fine, but loading of type 2 modules finishes with error: FRM-40735 PRE-FORM trigger raised unhandled exception ORA-06508.
    In both cases database schema and fmx/plx modules are the same.
    Implementation of WebForms is noncartridge
    (without Oracle Application Server).
    Clients use Jinitiator and IE4.
    Forms version is 5 + patch 7.
    DBMS version is 7.3.4.0.
    Thanks and regards.

    Two questions:
    Are you running your application against one DB, while it was compiled against another?
    If any of your forms or libraries is calling DB stored package that are passing parameters in between database and modules?
    If the answer to both questions is yes, then you're dealing with Oracle bug. Oracle support points to interaction between forms
    PL/SQL 8.0.5.1.0 and database PL/SQL 2.3.4.
    This problem should be fixed in the forms
    PL/SQL 8.1.6 which is not available at present time. The only work around is to maintain forms executable and/or compiled libraries for each of your DB.
    Good luck.
    null

  • JavaFX as a SaaS/ How good is it for Client-Server work?

    I was under the impression that FX could be used to produce a Client-Server application as well as SaaS.
    a member of another forum said "I'm sure you meant to say "Desktop". JavaFX will not be making inroads on the web as a client-side technology."
    To which I said
    There have been examples of FX used with EE
    http://www.oracle.com/technetwork/java/javafx/samples/index.html
    http://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm
    Sales Dashboard (DataApp)
    DataApp is a client-server application for a fictional global automobile company called Henley Car Sales. Automobile sales are simulated on an EJB server using JavaDB, and the data is available via Derby and a RESTful web service. The client demonstrates a variety of data presentations by using a mix of FXML and JavaFX.
    I thought originally that JavaFX was "Desktop" only also, until I found this example. I couldn't get it to run due to some weird Database line read issue that others also had. I'm not sure if this is now due to FX's integration, or if this was something new, but I believe I have seen another FX client-server app as well.
    I'm not that familiar with the client-server side of Java yet, so if you have other Information I would like to know, because I am looking to design a Client-Server app with FX, and I don't see why it would be an issue, unless there are huge limitations."
    He ended up saying "Those are still desktop apps. Sure, they are client-server in that they connect to a remote database. But they are still traditional fat-client apps rather than web-based thin-client SAAS web applications which, these days, most people will think of when you say "client".
    My point is to be more precise when you use the word "client".
    But if your point is just that JavaFX is taking over from Swing for the limited areas in which Swing is used, I have no insight into that area."
    Now I don't really like attitudes when I get my question answered, but the high and mighty needs to stop. It clearly says Client-Server so I don't know why it's being denounced by this dude who thinks he obviously knows better.
    Anyways he talks about it only being able to connect to a DB, to which it says it uses EE tech such as EBJ, Restful, and Derby, so that's more than just DB right(I don't know since I havent' learned that yet)?
    It seems as if he's saying that only EE code can go up on a server? Or can SE code go up there as well?
    I'm looking to design a SaaS software with FX, so if this isnt' possible I would like to know possible other options(or just having all of the gui work on the client, and the rest on the backend)???
    Thanks!
    ~KZ
    Edited by: KonradZuse on Apr 30, 2013 11:26 AM

    This response is not a tutorial, I hope it gives you some verbiage to use in further searches.
    SaaS to me means that the service is running on the server. If you have the server and permission to run java apps there then you can use Java FX by having the server shuttle requests to the Java FX app. But this is probably not the intent of Saas (it would be more appropriate to use a java implemented web service).
    If you are using Netbeans then it is very easy to create demo projects; use "File/New Project" to run them on your local computer.
    Example File/New Project/Java Web/Web Application will give you a hello world web site very quickly. This will 1) start either tomcat or glassfish as the server. 2) launch an html page with "hello world". then you can use java script to talk with the server via ajax. Using this approach you are going to need to study JSP or J2EE stuff.
    After this is running you could start one of the Java Fx examples in Netbeans: File / New Project / Samples / WebViewBrowser. This will start a javaFX app that acts like a browser and runs on the client.
    So, start the "hello world" app in netbeans by right clicking it in the project pain and selecting "debug". Then start the webviewBrowser app the same way to load that web page that has "hello world" in it as all browsers do. In the WebviewBrowser (which is java fx) you can get at the javascript in the web page and do all kinds of stuff. You'll need to search for webviewBrowser examples.
    The above all assumes a Netbeans solution. But, as you probably know, there are no rules. The server can be in C++ and the client in C (or any other language). The server and client usally communicate via http or tcp. So you could have a server written in java (maybe J2ee or you can rewrite a http server from scratch which isn't that hard - search for "HttpServletRequest and HttpSession" ) and the client can be in Java FX (where the Java FX talks directly with the server via http (no javascript or web page in the middle) again there are probably hundreds of libraries to talk to a http server).
    I use HttpServletRequest and HttpSession on the server side with MySQL and xml. On the client I use javaScript but I am moving to a strictly Java FX solution. This will give me close to 100% java on both sides and for my purposes this will work. (I may need a little html in the middle for drag and drop installation.) I am hoping that work continues with porting Java FX to most devices: Android, IOS, WinPhone. It is already on Linux, Windows Desktops and Mac.
    Edited by: KevinPas on May 1, 2013 9:50 AM
    Edited by: KevinPas on May 1, 2013 9:56 AM

  • Client-Server office discussion. Need a pattern ?

    Hello all,
    1. We are new in network programming, so please forgive us for such a dum question.
    In our last project we were requested to write a very simple java server which would handle some "Task process" state by recieving commands "start,stop,getStatus".
    Although we were able to easily write the code, we had a doubt that created a team discussion.
    Were should the socket connection be stablished ?
    Some of us stated that the "Constructor" should establish the connection to the socket, as the "Server" can not exists if it is not listening to a port.
    Some others stated that a "Run/Start" method should do this.
    Obviouly either way works, yet I'm hopping that the Gurus here can help us determine the right answer.
    2. I read about MVC pattern but I can't find a link to a well explained "Client-Server" pattern. Does anyone know a good place to find patterns ?
    Thanks in advanced for you help !!!
    It's great to be part of this community.
    Thanks..

    Hello all,
    1. We are new in network programming, so please
    forgive us for such a dum question.
    In our last project we were requested to write a very
    simple java server which would handle some "Task
    process" state by recieving commands
    "start,stop,getStatus".
    Although we were able to easily write the code, we
    had a doubt that created a team discussion.
    Were should the socket connection be stablished ?
    Some of us stated that the "Constructor" should
    establish the connection to the socket, as the
    "Server" can not exists if it is not listening to a
    port.
    Some others stated that a "Run/Start" method should
    do this.
    Obviouly either way works, yet I'm hopping that the
    Gurus here can help us determine the right answer.
    Why not use a Servlet? That having been said, if I did want to re-invent the wheel, I would add startListening() and stopListening() methods to the class that manages the ServerSocket. You can always force a JVM exit, but why not at least provide methods for callers that want to end gracefully?
    2. I read about MVC pattern but I can't find a link
    to a well explained "Client-Server" pattern. Does
    anyone know a good place to find patterns ?
    Thanks in advanced for you help !!!
    It's great to be part of this community.
    Thanks..Do a Google search on writing a multi-threaded server. A number of patterns could apply. Client-server is really an architecture, not a pattern. Any number of patterns (or anti-patterns) could actually implement it.
    - Saish

  • What is best way to secure client/server communication?

    Hi all, I have a question for you. What is the best method for ensuring a secure communication through a client/server stream socket implementation?
    I currently have a server that talks to several clients for various tasks. I would like to make all communication between the server and clients secure. In other words when one of my clients accepts an incoming connection I would like to verify that the server is really who they are talking with, and also that the data that is being received is indeed not tampered with.
    Is SSL the correct technology to use with this? And if so, what is the general outline of steps I need to follow to get an SSL connection? I mean do I need certificates and all that stuff?
    Thanks in advance for any help you may be able to provide.

    The more I look into SSL the more it appears it is only for web servers. My app is not web server based. Is SSL not the correct way to go on this then?

  • Client-Server side GUI programming

    I want to create a client-server side gui programming with java
    i read this web adress
    http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html
    for information but there are some parts that i didnt understand and wait for your help
    i m trying to build an online-help(live chat) system so when people press the start chat button a java page will appear but i wonder how this will connect to the person who is on server side
    i mean is it possible to 2 users connect the same port and chat with each other
    I mean when user press the chat button the online help supporter will be informed somebody wants to speak with him and they will start a chat
    how can i do something like that
    any help would be usefull thanks

    Below is an example of a client/server program.
    It shows how the server listens for multiple clients.
    * TriviaServerMulti.java
    * Created on May 12, 2005
    package server;
    * @author johnz
    import java.io.*;
    import java.net.*;
    import java.util.Random;
    * This TriviaServer can handle multiple clientSockets simultaneously
    * This is accomplished by:
    * - listening for incoming clientSocket request in endless loop
    * - spawning a new TriviaServer for each incoming request
    * Client connects to server with:
    * telnet <ip_address> <port>
    *     <ip_address> = IP address of server
    *  <port> = port of server
    * In this case the port is 4413 , but server can listen on any port
    * If server runs on the same PC as client use IP_addess = localhost
    * The server reads file
    * Note: a production server needs to handle start, stop and status commands
    public class TriviaServerMulti implements Runnable {
        // Class variables
        private static final int WAIT_FOR_CLIENT = 0;
        private static final int WAIT_FOR_ANSWER = 1;
        private static final int WAIT_FOR_CONFIRM = 2;
        private static String[] questions;
        private static String[] answers;
        private static int numQuestions;
        // Instance variables
        private int num = 0;
        private int state = WAIT_FOR_CLIENT;
        private Random rand = new Random();
        private Socket clientSocket = null;
        public TriviaServerMulti(Socket clientSocket) {
            //super("TriviaServer");
            this.clientSocket = clientSocket;
        public void run() {
            // Ask trivia questions until client replies "N"
            while (true) {
                // Process questions and answers
                try {
                    InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
                    BufferedReader is = new BufferedReader(isr);
    //                PrintWriter os = new PrintWriter(new
    //                   BufferedOutputStream(clientSocket.getOutputStream()), false);
                    PrintWriter os = new PrintWriter(clientSocket.getOutputStream());
                    String outLine;
                    // Output server request
                    outLine = processInput(null);
                    os.println(outLine);
                    os.flush();
                    // Process and output user input
                    while (true) {
                        String inLine = is.readLine();
                        if (inLine.length() > 0)
                            outLine = processInput(inLine);
                        else
                            outLine = processInput("");
                        os.println(outLine);
                        os.flush();
                        if (outLine.equals("Bye."))
                            break;
                    // Clean up
                    os.close();
                    is.close();
                    clientSocket.close();
                    return;
                } catch (Exception e) {
                    System.err.println("Error: " + e);
                    e.printStackTrace();
        private String processInput(String inStr) {
            String outStr = null;
            switch (state) {
                case WAIT_FOR_CLIENT:
                    // Ask a question
                    outStr = questions[num];
                    state = WAIT_FOR_ANSWER;
                    break;
                case WAIT_FOR_ANSWER:
                    // Check the answer
                    if (inStr.equalsIgnoreCase(answers[num]))
                        outStr="\015\012That's correct! Want another (y/n)?";
                    else
                        outStr="\015\012Wrong, the correct answer is "
                            + answers[num] +". Want another (y/n)?";
                    state = WAIT_FOR_CONFIRM;
                    break;
                case WAIT_FOR_CONFIRM:
                    // See if they want another question
                    if (!inStr.equalsIgnoreCase("N")) {
                        num = Math.abs(rand.nextInt()) % questions.length;
                        outStr = questions[num];
                        state = WAIT_FOR_ANSWER;
                    } else {
                        outStr = "Bye.";
                        state = WAIT_FOR_CLIENT;
                    break;
            return outStr;
        private static boolean loadData() {
            try {
                //File inFile = new File("qna.txt");
                File inFile = new File("data/qna.txt");
                FileInputStream inStream = new FileInputStream(inFile);
                byte[] data = new byte[(int)inFile.length()];
                // Read questions and answers into a byte array
                if (inStream.read(data) <= 0) {
                    System.err.println("Error: couldn't read q&a.");
                    return false;
                // See how many question/answer pairs there are
                for (int i = 0; i < data.length; i++)
                    if (data[i] == (byte)'#')
                        numQuestions++;
                numQuestions /= 2;
                questions = new String[numQuestions];
                answers = new String[numQuestions];
                // Parse questions and answers into String arrays
                int start = 0, index = 0;
                   String LineDelimiter = System.getProperty("line.separator");
                   int len = 1 + LineDelimiter.length(); // # + line delimiter
                boolean isQuestion = true;
                for (int i = 0; i < data.length; i++)
                    if (data[i] == (byte)'#') {
                        if (isQuestion) {
                            questions[index] = new String(data, start, i - start);
                            isQuestion = false;
                        } else {
                            answers[index] = new String(data, start, i - start);
                            isQuestion = true;
                            index++;
                    start = i + len;
            } catch (FileNotFoundException e) {
                System.err.println("Exception: couldn't find the Q&A file.");
                return false;
            } catch (IOException e) {
                System.err.println("Exception: couldn't read the Q&A file.");
                return false;
            return true;
        public static void main(String[] arguments) {
            // Initialize the question and answer data
            if (!loadData()) {
                System.err.println("Error: couldn't initialize Q&A data.");
                return;
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(4413);
                System.out.println("TriviaServer up and running ...");
            } catch (IOException e) {
                System.err.println("Error: couldn't create ServerSocket.");
                System.exit(1);
            Socket clientSocket = null;
            // Endless loop: waiting for incoming client request
            while (true) {
                // Wait for a clientSocket
                try {
                    clientSocket = serverSocket.accept();   // ServerSocket returns a client socket when client connects
                } catch (IOException e) {
                    System.err.println("Error: couldn't connect to clientSocket.");
                    System.exit(1);
                // Create a thread for each incoming request
                TriviaServerMulti server = new TriviaServerMulti(clientSocket);
                Thread thread = new Thread(server);
                thread.start(); // Starts new thread. Thread invokes run() method of server.
    }This is the text file:
    Which one of the Smothers Brothers did Bill Cosby once punch out?
    (a) Dick
    (b) Tommy
    (c) both#
    b#
    What's the nickname of Dallas Cowboys fullback Daryl Johnston?
    (a) caribou
    (b) moose
    (c) elk#
    b#
    What is triskaidekaphobia?
    (a) fear of tricycles
    (b) fear of the number 13
    (c) fear of kaleidoscopes#
    b#
    What southern state is most likely to have an earthquake?
    (a) Florida
    (b) Arkansas
    (c) South Carolina#
    c#
    Which person at Sun Microsystems came up with the name Java in early 1995?
    (a) James Gosling
    (b) Kim Polese
    (c) Alan Baratz#
    b#
    Which figure skater is the sister of Growing Pains star Joanna Kerns?
    (a) Dorothy Hamill
    (b) Katarina Witt
    (c) Donna De Varona#
    c#
    When this Old Man plays four, what does he play knick-knack on?
    (a) His shoe
    (b) His door
    (c) His knee#
    b#
    What National Hockey League team once played as the Winnipeg Jets?
    (a) The Phoenix Coyotes
    (b) The Florida Panthers
    (c) The Colorado Avalanche#
    a#
    David Letterman uses the stage name "Earl Hofert" when he appears in movies. Who is Earl?
    (a) A crew member on his show
    (b) His grandfather
    (c) A character on Green Acres#
    b#
    Who created Superman?
    (a) Bob Kane
    (b) Jerome Siegel and Joe Shuster
    (c) Stan Lee and Jack Kirby#
    b#

Maybe you are looking for

  • Changing field lable (header) in Table control.

    Hi all,         I am currently working on a table control. The requirement is to change the label in the column heading dynamically based on few conditions. Could any one please help me in finding out a way for changing the heading labels dynamically

  • Macmini and LCD 37" Philips 9986. what appened?

    Hi, I bought my first mac and I was really happy to finally change from the Windows mediacenter. I own a Philips 37" 9986 LCD television with DVI and the macmini connected with DVI cable. For two weeks everything worked properly but suddenly powering

  • Broadcast traffic with LCD Projector

    Hi all, Please help... how to enable broadcast traffic on WiSM on same VLAN/Interface... i have a LCD Projector that when the client do automatic search.. the client will broadcast to 255.255.255.255 and somehow the the LCD Projetor do not respond fo

  • My bluetooth seems just to search without connecting...

    My bluetooth seems just to search without connecting and finding any phones, PCs. If I send the transfer from another phone or pc, it does ask to pair up but always says not supported. Anyone knows how to fix this issue?

  • Automate BT FON login on Windows 7

    Hi, As per the title, is there a way to automate the BT FON login on Windows 7 (i.e the equivalent of the BT FON app on Android or iPhones etc)..? Cheers Simon