Simple Server/Client Applet example code ???

Hi to all.
I would like to ask if possible to someone to tell me some example code to do this simple thing:
I want an applet showing only a TextField and a button. When the user writes something on the textfield and press the button, it should send the text in the textfield to the "server", and then it should save it in a variable.
I think there should be 2 different classes at least (server and client), but no idea in how could I make this on Java.
So I am asking if possible for some sample code for make this.
Thank you for the information
John

hello!
Here is a console based Server which will recieve the string and disply on the DOS screen.
/////////////////////////////////// Server /////////////////
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer extends Thread
ServerSocket ssSocket;
Socket sSocket;
public BufferedReader in;
public PrintWriter out;
public ChatServer()
     try
     ssSocket = new ServerSocket (4000);
     catch(IOException e)
     System.out.println (e);
public void run()
try
     sSocket = ssSocket.accept();
     if(sSocket != null)
          in = new BufferedReader(new InputStreamReader(sSocket.getInputStream()));
          out = new PrintWriter(sSocket.getOutputStream(), true);
String str = in.readLine();
     System.out.println (str);
     catch(IOException e)
          System.out.println (e);
public static void main (String []args)
          Thread th = (Thread) new ChatServer();
          th.start();     
///////////////////////// Client //////////////////////
public class Client extends Applet implements ActionListener
public Socket sClient;
public BufferedReader in;
public PrintWriter out ;
String str;
private TextField txt = new TextField();
private Button btn = new Button ("OK");
public void init()
     try
     sClient = new Socket ("localhost" , 4000);
     in = new BufferedReader(new InputStreamReader(sClient.getInputStream()));
     out = new PrintWriter(sClient.getOutputStream(), true);
     catch (UnknownHostException uhe)
     catch (IOException ioe)
     System.out.println (" I/O Exception : " + ioe);
     setLayout(new FlowLayout());
     txt.setColumns (20);
     add(txt);
     add(btn);
     btn.addActionListener(this);
public void actionPerformed(ActionEvent AE)
     if(AE.getSource() == btn)
     str = txt.getText();
     out.println(str);
now u should try it and improve it according to ur need...
Ahmad Jamal.

Similar Messages

  • Server/Client applet sample code ???

    Hi to all.
    I would like to ask if possible to someone to tell me some example code to do this simple thing:
    I want an applet showing only a TextField and a button. When the user writes something on the textfield and press the button, it should send the text in the textfield to the "server", and then it should save it in a variable.
    I think there should be 2 different classes at least (server and client), but no idea in how could I make this on Java.
    So I am asking if possible for some sample code for make this.
    Thank you for the information
    John

    here is code for applet..
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class MyApplet extends Applet
          implements ActionListener {
      TextField tf;
      Button btn;
      public void init() {
        setLayout(null);
        tf = new TextField();
        tf.setBounds(5,5,80,20);
        btn = new Button("send message to server");
        btn.setBounds(5,30,150,20);
        btn.addActionListener(this);
        add(tf);
        add(btn);
      public void actionPerformed(ActionEvent ae) {
        sendMessage();
      void sendMessage() {
        String msg = tf.getText().trim();
        tf.setText("");
        if(msg==null) return;
        try {
          // this is using a direct socket connection..
          Socket s = new Socket("www.blah.com",80);
          ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
          oos.writeObject(msg);
          oos.flush();
          ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));
          String response = (String) ois.readObject();
          System.out.println("response received="+response);
          ois.close();
          oos.close();
          s.close();
        } catch (Exception e) {
            System.out.println("error in sendMessage:"+e);
    }here is the html code..
    <applet code=MyApplet width=180 height=55></applet>
    let me know if u need more help.
    good luck.

  • SocketPermissions for Chat Server/Client Applet

    Hi,
    I've coded a chat server/client applet and found that I need to set socketpermissions when using over the net.
    I put the following line in my java.policy file under my jdk
    permission java.net.SocketPermission ":6288", "connect,accept, listen";
    but it still tells me:
    java.security.AccessControlException: access denied(java.net.SocketPermission 217.0.0.1:6288 connect, resolve)
    any ideas? or am I doing something wrong?
    Also I havent set anything for my applet, and wouldnt know how to? if you do have to set permissions for that, do you put the permissions in with the code or something?
    Thanks in advance.
    Matt.

    ah, dont worry, I've got it fixed.
    that 217.0.0.1 address is because I typed the error by the way, usually it would have my IP.
    problem was I had forgot to recompile with my new assigned IP, d'oh!

  • Simple server/client socket in applets code.

    Can anyone please help me with Java sockets ? I want to create an applet that simply checks if it's still online. This means that i'll be using this applet thru modem(that is, dial-up connection). All i want the applet to do is send a signal to the server and the server answer back that it is still online. The server should be able to handle multiple sends and receives. I need just a simple code for me to work on (both server and client). The client doesn't have to send any special message to the server and vice versa.
    Thanks.

    Below is the code for both Applet and Servlet .I think this will solve your problem.
    Applet:
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    public class OnlineApplet extends Applet implements Runnable
         private static Thread thread;
         private static HttpURLConnection URLConn;
         public void init()
              try
                   //Connect to the URL where servlet is running.
                   URL url = new URL("http://localhost/servlet/OnlineServlet");
                   URLConn = (HttpURLConnection)url.openConnection();
                   URLConn.setDoInput(false);
                   URLConn.setDoOutput(true);
              catch (Exception ex)
              thread = new Thread(this);
         public void start()
              thread.start();
         public void paint(Graphics g) {}
         public void stop() { }
         public void destroy() { }
         public void run()
              while(true)
                   try
                        thread.sleep(1000 * 60);
                        sendConfirmation();
                   catch (Exception ex)
         private void sendConfirmation() throws Exception
              DataOutputStream dos = new DataOutputStream(URLConn.getOutputStream());
              dos.writeChars("Fine");
              dos.flush();
              dos.close();
    Servlet:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class OnlineServlet extends HttpServlet implements Runnable
         public static Hashtable hsh;
         private static Thread thread;
         public void init(ServletConfig scon) throws ServletException
              hsh = new Hashtable();
              thread = new Thread(this);
         public void service(HttpServletRequest req, HttpServletResponse res)
              String strHostName = req.getRemoteHost();
              if(hsh.containsKey(strHostName))
                   updateHash(strHostName);
              else
                   hsh.put(strHostName, System.currentTimeMillis() + "");
         private void updateHash(String strHostName)
              hsh.remove(strHostName);
              hsh.put(strHostName, System.currentTimeMillis() + "");
         public void run()
              while(true)
                   try
                        thread.sleep(1000 * 120);
                   catch (Exception ex)
                   validateUsers(System.currentTimeMillis());
         private void validateUsers(long msec)
              Enumeration keys = hsh.keys();
              int size = hsh.size();
              while(keys.hasMoreElements())
                   String strKey = keys.nextElement().toString();
                   String strLong = hsh.get(strKey).toString();
                   long lg1 = Long.parseLong(strLong);
                   if((lg1 - msec) > 100000)
                        // This means there is no response from user . That means he is not online. So you can remove from hashtable.
                        hsh.remove(strKey);

  • Java3D Non-Applet Example Code

    Hi, i've been searching far and wide for an example of Java3D code that is NOT used inside an applet. If someone could please post the most basic elements of a Java3D program used in an application, I would greatly appreciate it. Thank you! If you know of any websites with example applications, please post those here as well.

    ...or add a main-method that makes your applet runnable as an application as well!
    public static void main( String[] params){
        com.sun.j3d.utils.applet.MainFrame frame= new  com.sun.j3d.utils.applet.MainFrame(
            new YourApplet(), 800,600);
    }

  • My first Server/Client Program .... in advise/help

    Hello,
    I am learning about Sockets and ServerSockets and how I can use the. I am trying to make the simplest server/client program possible just for my understanding before I go deper into it. I have written two programs. theserver.java and theclient.java the sere code looks like this....
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class theserver
      public static void main(String[] args)
      {   //  IOReader r = new IOReader();
            int prt = 3333;
            BufferedReader in;
             PrintWriter out;
            ServerSocket serverSocket;
            Socket clientSocket = null;
    try{
    serverSocket = new ServerSocket(prt);  // creates the socket looking on prt (3333)
    System.out.println("The Server is now running...");
    while(true)
        clientSocket = serverSocket.accept(); // accepts the connenction
        clientSocket.getKeepAlive(); // keeps the connection alive
        out = new PrintWriter(clientSocket.getOutputStream(),true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         if(in.ready())
         System.out.println(in.readLine()); // print it
    catch (IOException e) {
        System.out.println("Accept failed:"+prt);
    and the client looks like this
    import java.net.*;
    import java.io.*;
    public class theclient
    public static void main(String[] args)
        BufferedReader in;
        PrintWriter out;
        IOReader r = new IOReader();
        PrintWriter sender;
        Socket sock;
      try{
        sock = new Socket("linuxcomp",3333);  // creates a new connection with the server.
        sock.setKeepAlive(true); // keeps the connection alive
        System.out.println("Socket is connected"); // confirms socket is connected.
        System.out.println("Please enter a String");
         String bob = r.readS();
          out = new PrintWriter(sock.getOutputStream(),true);
        out.print(bob); // write bob to the server
      catch(IOException e)
           System.out.println("The socket is now disconnected..");
    If you notice in the code I use a class I made called IOReader. All that class is, is a buffered reader for my System.in. (just makes it easier for me)
    Ok now for my question:
    When I run this program I run the server first then the client. I type "hello" into my system.in but on my server side, it prints "null" I can't figure out what I am doing wrong, if I am not converting correctly, or if the message is not ever being sent. I tried putting a while(in.read()) { System.out.println("whatever") } it never reaches a point where in.ready() == true. Kinda of agrivating. Because I am very new to sockets, I wanna aks if there is somthing wrong with my code, or if I am going about this process completely wrong. Thank you to how ever helps me,
    Cobbweb

    here's my simple server/client Socket :
    Server:
    import java.net.*;
    import java.io.*;
    public class server
       public static void main(String a[])
              ServerSocket server=null;
              Socket socket=null;
              DataInputStream input=null;
              PrintStream output=null;
          try
             server=new ServerSocket(2000);
             socket=server.accept();
             input = new DataInputStream(socket.getInputStream());
             output = new PrintStream(socket.getOutputStream());
             //output.println("From Server: hello there!");
             String msg="";
             while((msg=input.readLine()) != null)
                System.out.println("From Client: "+msg);
          catch(IOException e)
          catch(Exception e)
    }Client:
    import java.net.*;
    import java.io.*;
    public class client
       static private Socket socket;
       static private DataInputStream input;
       static private PrintStream output;
       public static void main(String a[])
          try
    socket=new Socket("10.243.21.101",2000);
    System.out.println("\nconnected to: \""+socket.getInetAddress()+"\"");
             input=new DataInputStream(socket.getInputStream());
             output=new PrintStream(socket.getOutputStream());
             output.println("From Client(Tux): "+a[0]);
             String msg="";
             //while((msg=input.readLine()) != null)
                 System.out.println("From Server(Bill): "+msg);
          catch(java.io.IOException e)
          catch(Exception e)
    }

  • Server/Client Socket Connection

    Hi, I am trying to program a simple server/client socket connection program, the main function is to send and receive objects between them. I somehow went wrong and the connection between them keeps terminating right after establishing connection. Is there anything I can do to resolve this?
    This is gonnna be kinda long post.. sorry. These are the code that starts and ends the socket connection. I'm kinda desperate for this to work.. so thanks in advance.
    appinterface.java:
    //Set up server to receive communications; process connections. 1x.
         public void runServer () {
              try {
                   //Create a ServerSocket
                   server = new ServerSocket(12345, 100);
                   try {
                             waitForSockConnection();     //Wait for a connection.
                             getSockStreams();               //Get input & output streams.
                             establishDbConnection();     //Open up connection to DB.
                   finally {
                             closeSockConnection(); //Close connection.
              //Process problems with I/O
              catch(IOException ioException) {
                   displayMessage("I/O Error: " + ioException);
                   runServer();
         //Wait for connection to arrive, then display connection info
         private void waitForSockConnection() throws IOException {
              displayMessage("Waiting for connection");
              connection = server.accept(); //Allow server to accept connection.
              displayMessage("Connection received from: " + connection.getInetAddress().getHostName());
         //Get streams to send and receive data.
         private void getSockStreams() throws IOException {
              //Set up output streams for objects
              ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
              output.flush(); //Flush output buffer to send header information.
              //Set up input stream for objects.
              ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
              try {
              classHolderServer holderObj = new classHolderServer();
              holderObj = (classHolderServer)input.readObject();
              processSockConnection(holderObj);
              displayMessage("Got I/O Streams");
              //Catch problems reading from client
              catch (ClassNotFoundException classNotFoundException) {
                             displayMessage("Unknown object type received");
         //Process connection with client.
         private void processSockConnection(classHolderServer holderObj) throws IOException {
              //sendMessage("Connection Successful");
                        //True is query, and false is auth.
                        if(holderObj.type1==true)
                             processDbStatement(holderObj.type2, holderObj.sqlquery);
                        else {
                             authCheck(holderObj.userName, holderObj.passWord);
                             if(!authCheck)
                             closeDbConnection();
         //Send messages to client.
         private void sendMessage(String message) {
              // Send message to client
              try {
                   ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
                   output.flush();
                   output.writeObject(message);
                   output.flush();
                   displayMessage("Message Sent:" + message);
              catch (IOException ioException) {
                   displayMessage("\nError Sending Message: " + message);
         //Send object to client
         private void sendObject(Object holderObj) {
                   // Send object to client
                   try {
                        ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
                        output.writeObject(holderObj);
                        output.flush();
                        displayMessage("\nObject sent");
                   //Process problems sending object
                   catch (IOException ioException) {
                        displayMessage("\nError writing object");
         //Close streams and socket.
         private void closeSockConnection() {
                   displayMessage("Terminating connection");
                   try {
                        //output.close();
                        //input.close();
                        connection.close();
                        closeDbConnection();
                        this.userName = null;
                        this.passWord = null;
                        this.receiverId = 0;
                        this.authCheck = false;
                   catch (IOException ioException) {
                        displayMessage("I/O Error: " + ioException);
              }Client:
    private void runClient() {
              //Connect to sever and process messages from server.
              try{
                   connectToServer();
                   getStreams();
                   processConnection();
              //Server closed connection.
              catch(EOFException eofException) {
                   //displayMessage"Client Terminated Connection");
              //Process problems communicating with server.
              catch (IOException ioException) {
                   //displayMessage"Communication Problem");
              finally {
                   closeConnection();
         //Connect to server
         private void connectToServer() throws IOException {
              //displayMessage("Attempting connection\n");
              //Create Socket to make connection to sever.
              client = new Socket(InetAddress.getByName(chatServer), 12345);
              //Display connection information
              //displayMessage("Connected to: " + client.getInetAddress().getHostName());
         //Get streams to send and receive data.
         private void getStreams() throws IOException {
              //Set up output stream for objects.
              ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
              output.flush(); //Flush outout buffer to send header information.
              //Set up input stream for objects.
              ObjectInputStream input = new ObjectInputStream(client.getInputStream());
              //displayMessage("\nGot I/O streams\n");
         //Close socket connection.
         private void closeConnection() {
              //displayMessage("\nClosing connection");
              try {
                   ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                   output.close();
                   ObjectInputStream input = new ObjectInputStream(client.getInputStream());
                   input.close();
                   client.close();
                   authCheck=false;
              catch(IOException ioException) {
                   ioException.printStackTrace();
         //Send data to server.
         private void sendObject(classHolderClient queryObj) {
              try {
                   output.writeObject(queryObj);
                   output.flush();
                   //displayMessage("Please wait..");
              //Process problems sending object.
              catch (IOException ioException) {
                   //displayMessage("\nError writing object");
         //Process connection with server.
         private void processConnection() throws IOException {
              try{
                   classHolderClient holderObj = new classHolderClient();
                   holderObj = (classHolderClient)input.readObject();
                   if(holderObj.type2==2) {
                             this.authCheck=holderObj.authCheck;
                             this.userName=holderObj.userName;
                             this.passWord=holderObj.passWord;
              catch(ClassNotFoundException classNotFoundException) {
                   //displayMessage(classNotFoundException);
              }

    private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());Like this? But this will cause an error asking me to catch an exception:
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
            private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                                                                                             ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
            private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                                                ^
    2 errors

  • Server/Client connection using an actionListener

    Hey guys,
    New to this board, so hopefully I can be of assistance :)
    What I am currently working on is a networked Monopoly game. My part of the assignment is to create a simple game lobby (just GUI based, buttons, action listeners, etc) where players can create games and join games already created.
    What I have is this. When a player clicks on the "Create Game" button, an anonomus inner action listener will detect the push and create a hosted game (Server side connection). When a player clicks on the newly created game, they will be a joined player (Client side connection).
    The problem is this, keep in mind that I have created a very, very simple server/client chat to test this out. When a Socket is created for the clients to connect to upon the Create Game button push, my program essentially just hangs. Nothing happens at all.
    Here are the 3 classes I used. I understand this is probably not the most efficient way to post, but this is the only way you can see what I exactly have. I took out all my GUI stuff to make it easier to follow (if you want me to post full classes I can):
    Thanks for all the help!
    - Ry
    //package Mackopoly;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.io.EOFException;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    public class gameList extends JFrame {
        MackPlayer tc1;
        MackPlayer tc2;
        MackPlayer tc3;
        HostPlayer ts1;
        HostPlayer ts2;
        HostPlayer ts3;
        private String temp = ""; //used to display chat area
        private int gameCounter = 0; //number of games created
        private boolean game1Started = false;
        private boolean game2Started = false;
        private boolean game3Started = false;
        public void start()
        //Sets up the screen
            enterField.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == enterField)
                        temp = enterField.getText();
                        chatBox.append(temp + "\n");
                        enterField.setText("");
            createGame.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == createGame)
                        gameCounter++;
                        if(gameCounter == 1)
                            //create a new host game on the server
                            //instanciate an object accordingly
                            game1.setText("Game " + gameCounter + "started!");
                            game1Started = true;
                                  ts1 = new HostPlayer();
                            ts1.execute();
                        else if(gameCounter == 2)
                            game2.setText("Game " + gameCounter + "started!");
                            game2Started = true;
                                  ts2 = new HostPlayer();
                            ts2.execute();
                        else if(gameCounter == 3)
                            game3.setText("Game " + gameCounter + "started!");
                            game3Started = true;
                                  ts3 = new HostPlayer();
                             ts3.execute();
                        else
                            System.out.println("games full");
            joinGame1.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == joinGame1)
                        if(game1Started == false)
                            JOptionPane.showMessageDialog(null,"Start a game!");
                        if(game1Started == true)
                            JOptionPane.showMessageDialog(null,"Joined!");
                            tc1 = new MackPlayer("Game 1");
                            tc1.startClient();
            joinGame2.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == joinGame2)
                        if(game2Started == false)
                            JOptionPane.showMessageDialog(null,"Start a game!");
                        if(game2Started == true)
                             JOptionPane.showMessageDialog(null,"Joined!");
                            tc2 = new MackPlayer("Game 2");
                            tc2.startClient();
            joinGame3.addActionListener(
            new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    if (ae.getSource() == joinGame3)
                        if(game3Started == false)
                            JOptionPane.showMessageDialog(null,"Start a game!");
                        if(game3Started == true)
                             JOptionPane.showMessageDialog(null,"Joined!");
                            tc3 = new MackPlayer("Game 3");
                            tc3.startClient();
        }//End start method
    }//End of my class
    import java.awt.*;
    import java.awt.event.*;
    import java.net.Socket;
    import java.net.InetAddress;
    import java.io.IOException;
    import javax.swing.*;
    import java.util.Formatter;
    import java.util.Scanner;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    //Imports necessary packages
    public class MackPlayer extends JFrame implements Runnable
    //Client class
         private JTextField idField;
         private JTextArea displayArea;
         private JTextField guessArea;
         private JPanel panel2;
         private Socket connection;
         private Scanner input;
         private Formatter output;
         private String Host;
         private String myMark;
         private boolean myTurn;
         private final String X_MARK = "1";
         private final String O_MARK = "2";
         public MackPlayer(String host)
              Host = host;
              displayArea = new JTextArea(10,30);
              displayArea.setEditable(false);
              add(new JScrollPane(displayArea), BorderLayout.SOUTH);
              //Creates the message area
              idField = new JTextField();
              idField.setEditable(false);
              add(idField, BorderLayout.NORTH);
              //Creates the name field
              guessArea = new JTextField(10);
              guessArea.setEditable(false);
              add(new JScrollPane(guessArea), BorderLayout.CENTER);
              //Creates the guess area
              panel2 = new JPanel();
              panel2.add(guessArea, BorderLayout.CENTER);
              add(panel2, BorderLayout.CENTER);
              setSize(350, 275);
              setVisible(true);
              TextHandler tHandler = new TextHandler();
              idField.addActionListener(tHandler);
              guessArea.addActionListener(tHandler);
              //Adds the area's to the handler
              startClient();
         public void startClient()
         //Gets connection and starts thread
              try
                   connection = new Socket(InetAddress.getByName(Host), 12345);
                   input = new Scanner(connection.getInputStream());
                   output = new Formatter(connection.getOutputStream());
              catch(IOException e)
                   e.printStackTrace();
              ExecutorService worker = Executors.newFixedThreadPool(1);
              worker.execute(this);
         public void run()
              myMark = input.nextLine();
              SwingUtilities.invokeLater(
              new Runnable()
                   public void run()
                        idField.setText("Enter name here");
                        guessArea.setText("Enter guess");
                        //Default text
              );//end call
              myTurn = (myMark.equals(X_MARK));
              while(true)
                   if(input.hasNextLine())
                        processMessage(input.nextLine());
         private void processMessage(String message)
         //Handles all possible messages from the server
              if(message.equals("Guess too low."))
                   displayMessage("Guess too low\n");
              else if(message.equals("Guess too high."))
                   displayMessage("Guess too high\n");
              else if(message.equals("You Win!"))
                   displayMessage("You Win!\n");
              else if(message.equals("Other player connected.  Your turn."))
                   displayMessage("Other player connected.  Your turn\n");
                   guessArea.setEditable(true);
              else if(message.equals("Name1"))
                   displayMessage("Enter your name.\n");
                   idField.setEditable(true);
              else if(message.equals("Name2"))
                   displayMessage("Enter your name.\n");
                   idField.setEditable(true);
              else if(message.equals("Player 2 has entered name"))
                   displayMessage("Player 2 has entered name.  Your turn\n");
                   guessArea.setEditable(true);
              else if(message.equals("Invalid guess, try again"))
                   displayMessage(message + "\n");
                   myTurn = true;
                   guessArea.setEditable(true);
              else if(message.equals("Opponent guessed"))
                   int sw = input.nextInt();
                   displayMessage("Opponent guessed " + sw);
                   sendGuess(sw);
                   displayMessage("\nOpponent moved.  Your turn.\n");
                   guessArea.setEditable(true);
              else if(message.equals("Opponent guessed and won"))
                   int sw = input.nextInt();
                   displayMessage("Opponent guessed and won with number " + sw);
                   sendGuess(sw);
                   guessArea.setEditable(false);
              else
                   displayMessage(message + "\n");
         private void displayMessage(final String messageToDisplay)
              SwingUtilities.invokeLater(
              new Runnable()
                   public void run()
                        displayArea.append(messageToDisplay);
         public void sendGuess(int guess)
              if(myTurn)
                   output.format("%d\n", guess);
                   output.flush();
         private class TextHandler implements ActionListener
         //Handles the fields
              public void actionPerformed(ActionEvent event)
                   if(event.getSource() == idField)
                        idField.setEditable(false);
                        output.format("%s\n", idField.getText());
                        output.flush();
                        myTurn = false;
                        //Sends the name to the server
                        //Sets text to the name and sets it uneditable and sets turn to false
                   if(event.getSource() == guessArea)
                        guessArea.setEditable(false);
                        output.format("%s\n", guessArea.getText());
                        output.flush();
                        guessArea.setText("");
                        myTurn = false;
                        //Send the guess to the server
                        //Clears the past guess from the screen
    import java.awt.BorderLayout;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.IOException;
    import java.util.*;
    import javax.swing.*;
    import java.util.concurrent.*;
    import java.util.concurrent.locks.*;
    //Imports necessary packages
    public class HostPlayer extends JFrame
    //Server class
         private JTextArea outputArea;
         private Player[] players;
         private ServerSocket server;
         private int currentPlayer;
         private final static int PLAYER_1 = 0;
         private final static int PLAYER_2 = 1;
         private final static String[] MARKS = { "1", "2"};
         private ExecutorService runGame;
         private Lock gameLock;
         private Condition otherPlayerConnected;
         private Condition otherPlayerTurn;
         private Random generator = new Random();
         private int randomNumber;
         private String p1Name, p2Name;
         //Variables
         public HostPlayer()
              super("Guessing game");
              //Title of server window
              runGame = Executors.newFixedThreadPool(2);
              //Hanldes up to two clients
              gameLock = new ReentrantLock();
              //The lock
              otherPlayerConnected = gameLock.newCondition();
              otherPlayerTurn = gameLock.newCondition();
              //The condition variables
              players = new Player[2];
              currentPlayer = PLAYER_1;
              //The players
              try
                   server = new ServerSocket(12345, 2);
              catch(IOException e)
                   e.printStackTrace();
                   System.exit(1);     
              //Establishes server
              randomNumber = generator.nextInt(10);
              //The number to be guessed 0-10
              outputArea = new JTextArea();
              add(outputArea, BorderLayout.CENTER);
              outputArea.setText("Server awaiting connections \n");
              //The output area
              displayMessage("The number is " + randomNumber + " \n");
              //Prints out what the number is
              setSize(300, 300);
              setVisible(true);
              //Sets the size of the server window
         public void execute()
              for(int i = 0; i < players.length; i++)
                   try     
                        players[i] = new Player(server.accept(), i);
                        runGame.execute(players);
                        //Runs the threads to handle clients
                   catch(IOException e)
                        e.printStackTrace();
                        System.exit(1);
              gameLock.lock();
              try
                   players[PLAYER_1].setSuspended(false);
                   otherPlayerConnected.signal();
              finally
                   gameLock.unlock();
         private void displayMessage(final String messageToDisplay)
         //Function that displays messages
              //Class + method that can update the GUI for threads
              SwingUtilities.invokeLater(
              new Runnable()
                   public void run()
                        outputArea.append(messageToDisplay);
         public boolean validateAndMove(int guess, int player)
         //Function that determines what the output should be based on the guess
              while(player != currentPlayer)
              //The player can only guess if it is his turn
                   gameLock.lock();
                   try
                        otherPlayerTurn.await();
                   catch(InterruptedException e)
                        e.printStackTrace();
                   finally
                        gameLock.unlock();
              if(correctRange(guess))
              //If the guess is a valid guess
                   currentPlayer = (currentPlayer + 1) % 2;
                   //Switches player turn
                   players[currentPlayer].otherPlayerGuessed(guess);
                   gameLock.lock();
                   try
                        otherPlayerTurn.signal();
                        //Signals other player
                   finally
                        gameLock.unlock();
                   return true;
              else
                   return false;
         public boolean correctRange(int guess)
         //Tests for a valid guess between 0-10
              if(guess >= 0 && guess <= 10)
                   return true;
              else
                   return false;
         private class Player implements Runnable
         //Player class
              private Socket connection;
              private Scanner input;
              private Formatter output;
              private int playerNumber;
              private String mark;
              private boolean suspended = true;
              private boolean game = true;
              public Player(Socket socket, int number)
                   playerNumber = number;
                   mark = MARKS[playerNumber];
                   connection = socket;
                   try
                   //Tries to get the data streams
                        input = new Scanner(connection.getInputStream());
                        output = new Formatter(connection.getOutputStream());
                   catch(IOException e)
                        e.printStackTrace();
                        System.exit(1);
              public void otherPlayerGuessed(int guess)
              //Function that detemines whether the guess is too high/low or correct
                   if(guess == randomNumber)
                        output.format("Opponent guessed and won\n");
                        output.format("%d\n", guess);
                        output.flush();
                   else
                        output.format("Opponent guessed\n");
                        output.format("%d\n", guess);
                        output.flush();
              public void run()
              //The start of the threads, at the beginning messages go back and forth to set up the connection
              //and player names
                   try
                        displayMessage("Player " + mark + "connected \n");
                        output.format("%s\n", mark);
                        output.flush();
                        //Sends the message that the player has connected
                        if(playerNumber == PLAYER_1)
                             output.format("%s\n%s", "Player 1 connected ", "Waiting for another player\n");
                             output.flush();
                             gameLock.lock();
                             try
                                  while(suspended)
                                       otherPlayerConnected.await();
                                       //Waits for player 2
                             catch(InterruptedException e)
                                  e.printStackTrace();
                             finally
                                  gameLock.unlock();
                             output.format("Name1\n");
                             output.flush();     
                             p1Name = input.nextLine();
                             displayMessage("Player 1 = " + p1Name + "\n");
                             //Sends a message to enter the name and puts the received name
                             //in the variable p1Name
                             output.format("Other player connected. Your turn.\n");
                             output.flush();
                             //Starts the game when the other player has connected
                             //A lot of the turn base is done with message handling
                             //on the client side     
                        else
                             output.format("Name2\n");
                             output.flush();
                             p2Name = input.nextLine();
                             displayMessage("Player 2 = " + p2Name + "\n");
                             output.format("Player 2 connected. Please wait.\n");
                             output.flush();
                             //Sets up player 2's name and turn
                        while(game)
                        //while the game is not over
                             int guess = 0;
                             if(input.hasNext())
                                  guess = input.nextInt();
                             }//Gets next input
                             if(validateAndMove(guess, playerNumber))
                             //Sends the correct output based on the guess
                                  if(guess < randomNumber)
                                       if(playerNumber == 0)
                                            displayMessage(" \n"+p1Name+ " guess: " + guess);
                                       else
                                            displayMessage(" \n" p2Name " guess: " + guess);
                                       output.format("Guess too low.\n");
                                       output.flush();
                                  else if(guess > randomNumber)
                                       if(playerNumber == 0)
                                            displayMessage(" \n"+p1Name+ " guess: " + guess);
                                       else
                                            displayMessage(" \n" p2Name " guess: " + guess);
                                       output.format("Guess too high.\n");
                                       output.flush();
                                  else
                                       if(playerNumber == 0)
                                            displayMessage(" \n"+p1Name+ " guess: " + guess);
                                       else
                                            displayMessage(" \n" p2Name " guess: " + guess);
                                       output.format("You Win!\n");
                                       output.flush();
                                       game = false;
                                       //Ends game
                             else
                                  output.format("Invalid guess, try again\n");
                                  output.flush();
                   finally
                        try
                             connection.close();
                        catch(IOException e)
                             e.printStackTrace();
                             System.exit(1);
              }//End run
              public void setSuspended(boolean status)
                   suspended = status;
         }//End player class
    }//End Server class
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Thanks for the response
    I think I understand what you are saying, I just want to make sure I get it fully. I need to create a separate thread that runs just my connection process to make sure that the processes actually occur? If so, how would I go about doing this?
    Thanks again

  • Please tell me how to use the Simple bluetooth client server example.

    Hi i used the simple bluetooth client server example in labview 7.1. Iam getting an error saying your system does not support the network operation.  I have following doubts also.
    1. Should i pair the device before running the labview.
    2. Should i enable the file transfer wizard in the software given with the bluetooth adapter.
    Please help
    Thank you
    R.Prem kumar 
    09940446193

    Hi R.Prem,
    Could you please let me know what error code is associated with this error message? Also could you please provide a description of the setup you are currently using? Thanks!
    Best regards,
    Steven

  • Simple example code to connect to SQL server 2002

    Hi,
    I found a good website a while back which showed step by step how to connect to a sql server DB using JDBC, a re-install of windows means I cant find it again. I have searched the web, but to no avail. Basically I need to find a step by step guide to using java to access data within MS SQL server 2000. It needs to include details about where to download suitable drivers etc. and example code so that I can originally test my connection before diving much deeper.
    Any help much appreciated.

    Hi:
    here is the code that you can use it to test your connect if you use MS sql 2000 free driver. Others, you need to make little change on
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); and
    con = .......... parts
    goog luck !
    import java.sql.*;
    public class Connect{
    private java.sql.Connection con = null;
    private final String url = "jdbc:microsoft:sqlserver://";
    private final String serverName= "localhost";
    private final String portNumber = "1433";
    private final String databaseName= "pubs";
    private final String userName = "xxxxx";
    private final String password = "xxxxx";
    // Informs the driver to use server a side-cursor,
    // which permits more than one active statement
    // on a connection.
    private final String selectMethod = "cursor";
    // Constructor
    public Connect(){}
    private String getConnectionUrl(){
    return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
    private java.sql.Connection getConnection(){
    try{
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
    if(con!=null) System.out.println("Connection Successful!");
    }catch(Exception e){
    e.printStackTrace();
    System.out.println("Error Trace in getConnection() : " + e.getMessage());
    return con;
    Display the driver properties, database details
    public void displayDbProperties(){
    java.sql.DatabaseMetaData dm = null;
    java.sql.ResultSet rs = null;
    try{
    con= this.getConnection();
    if(con!=null){
    dm = con.getMetaData();
    System.out.println("Driver Information");
    System.out.println("\tDriver Name: "+ dm.getDriverName());
    System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
    System.out.println("\nDatabase Information ");
    System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
    System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
    System.out.println("Avalilable Catalogs ");
    rs = dm.getCatalogs();
    while(rs.next()){
    System.out.println("\tcatalog: "+ rs.getString(1));
    rs.close();
    rs = null;
    closeConnection();
    }else System.out.println("Error: No active Connection");
    }catch(Exception e){
    e.printStackTrace();
    dm=null;
    private void closeConnection(){
    try{
    if(con!=null)
    con.close();
    con=null;
    }catch(Exception e){
    e.printStackTrace();
    public static void main(String[] args) throws Exception
    Connect myDbTest = new Connect();
    myDbTest.displayDbProperties();

  • Need an example of server / client program with swing interface

    Hi!
    After a lot of trying i still haven't managed to create a server client program using swing components ...
    can someone write a mini application to demonstrate how this can be done?
    i would like to have a frame with a button a texField for input and a textAread for the output
    What i have in mind is the following ..
    say im the server
    i write something in the textField and then i press the button
    then the information written in the textFiled is passed to the client who shows it in his textArea
    The same thing goes on with the client (he can write something in his own textField and when he presses the button the info is passed at the
    server who puts it in his textArea) and vice versa.
    i have written many classes that trying unsuccessfully to do that ... below i show my last attempt ...
    I would appreciate if you could write a small application which it could to this.
    The whole idea is to create a turn based game ( i have implemented the game engine and graphics and i try to add the internet function)
    Here is the code ...( i would appreciate if you write a new code instead of trying to correct mine ( which i think it's impossible) in order to use it as a general example)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    *  In order to have a more gereral program instead of passing strings between the server
    *  and the client a pass an MyObjext object.  The MyObject class has an integer and a String
    *  (which is always the same) field . At the textField i write an integer number and i
    *  make a new MyObject which i want to pass to the server or the client and vice versa.
    *  The textArea shows the integer value of the MyObject which was passed from the server /client
    public class MyUserInterface extends JFrame {
         MyObject returnObject;
         JTextField myTextField;
         JTextArea te ;
         ClientGame cg;
         ServerGame sg;
          * used to determine if the current instance is running as a client or host
         boolean isHost;
         //The constructor of the client
         public MyUserInterface(ClientGame cg){
              this("Client");
              this.cg = cg;
              isHost = false;
         //The constructor of the server
         public MyUserInterface(ServerGame sg){
              this("Server");
              this.sg = sg;
              isHost = true;
         //The general constructor used both by client and server ..
         // it initializes the GUi components and add an actionListenr to the button
         public MyUserInterface(String str) {
              super(str);
              myTextField = new JTextField(2);
              te = new JTextArea();
              te.setPreferredSize(new Dimension(100,100));
              JButton okButton = new JButton("Ok");
              okButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        try{
                             int a = Integer.parseInt(MyUserInterface.this.myTextField.getText());
                             System.out.println(a);   //used to control the flow of the program
                                  MyUserInterface.this.returnObject = new MyObject(a);
                             //sends the data
                             sendData();
                             //waiting for response...
                             getData();
                             catch(Exception ex){System.out.println("Error in the UI action command" +
                                                                ex.printStackTrace();}
              JPanel panel =  new JPanel(new FlowLayout());
              panel.add(okButton);
              panel.add(myTextField);
              panel.add(te);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              getContentPane().add(panel);
              pack();
              setVisible(true);
         protected MyObject getReturnObject() {
              return returnObject;
         public void sendData(){
              new Thread(new Runnable() {
                   @Override
                   public void run() { 
                        if (!isHost)cg.sentData(returnObject);    //using the Servers out and in methods
                        else sg.sentData(returnObject);                    //using the Clients out and in methods
                        System.out.println("data sending");
         public MyObject getData(){
              MyObject obj;
              System.out.println("Retrieveing Data");
              if (!isHost)obj = (MyObject)cg.getData();
              else obj = (MyObject)sg.getData();
              System.out.println(" data retrieved  = "+ obj.getInt());  //just to control how the code flows
              te.setText(obj.getInt()+"");       
              return obj;
         public static void main(String[] args) {
              *Initiating the Server
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ServerGame sg = new ServerGame();
                        new MyUserInterface(sg);
              }).start();     
               * Initiating the Client
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ClientGame cg = new ClientGame("192.168.178.21");   //<----in case you run my code
                                                                          //..don't forget to change to your
                        new MyUserInterface(cg);                              //ip
              }).start();
    import java.io.*;
    import java.net.*;
    public class ClientGame {
         String ipAddress;
         Socket clientSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ClientGame(String ipAddress) {
              this.ipAddress = ipAddress;
              try {
                   System.out.println("Connecting To Host");
                 clientSocket = new Socket(InetAddress.getByName(ipAddress),4444);
                System.out.println("Host Found ...Io initializaton");
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
         public Object getData(){
              Object fromServer = null ;
              do{
                 try {
                      fromServer = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromServer==null);
              return fromServer;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                             out.writeObject(obj);
                        catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
              catch (IOException e){}
    public class ServerGame {
         ServerSocket serverSocket;
         Socket clientSocket;
         ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ServerGame() {
              try{
                   serverSocket = new ServerSocket(4444);
                   clientSocket = serverSocket.accept();
                   out =  new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
              catch(IOException e){System.out.println("IOException in ServerGame");}
         public Object getData(){
              Object fromClient = null ;
              do{
                 try {
                      fromClient = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromClient==null);
             return fromClient;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                   out.writeObject(obj);
              catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
                   serverSocket.close();
              catch (IOException e){}
         public static void main(String[] args) {
              new ServerGame();
    import java.io.Serializable;
    * this is a test object
    * it has a String field and a value
    *  The string is always the same but the integer value is defined in the constructor
    public class MyObject implements Serializable{
         private static final long serialVersionUID = 1L;
         String str;
         int myInt;
         MyObject(int a){
              str = "A String";
              myInt = a;
         public int getInt(){
              return myInt;
    }

    Pitelk wrote:
    I believe that a good code example can teach you things ;that you would need many days of searching; in no timeSo lets write one small example.. Ill help a little, but you do most of the work.
    jverd approach is deffenetly the way to go.
    jverd wrote:
    * Write a very small, simple Swing program with an input area, an output area, and a button. When you click the button, what's in the input area gets copied over to the output area.This part is partially done.
    * Write a very small, simple client/server program without Swing. It should just send a couple of hardcoded messages back and forth.And this part is for you(Pitelk) to continue on. I cannot say that this is the best way. or that its good in any way. I do however like to write my client/server programs like this. And perhaps, and hopefully, Ill learn something new from this as well.
    This is how far I got in about 10-20min..
    package client;
    * To be added;
    * A connect method. That connects the client to the server and
    * opens up both the receive and transmit streams. After doing that
    * the an instance of the ServerListener class should be made.
    * Also an disconnect method could be usable. But thats a later part.
    public class TestClass1 {
    package utils;
    import java.io.ObjectInputStream;
    import client.TestClass1;
    * This class is meant to be listening to all responses given from
    * the server to the client. After a have received data from the
    * server. It should be forwarded to the client, in this case
    * TestClass1.
    public class ServerListener implements Runnable {
         public ServerListener(ObjectInputStream in, TestClass1 tc) {
         @Override
         public void run() {
              while(true) {
    package server;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    * This class should handle all data sent to the server from the clients.
    class Server implements Runnable {
         private static List<ObjectOutputStream> outStreams = new ArrayList<ObjectOutputStream>();
         private Socket client = null;
         public Server(Socket client) {
              this.client = client;
         @Override
         public void run() {
              while(true) {
    * The meaning of this class is to listen for clients trying to connect
    * to the server. Once connection is achieved a new thread for that client
    * should be made to listen for data sent by the client to the server.
    public class ChatServer implements Runnable {
         @Override
         public void run() {
              while(true) {
    package utils;
    import java.io.Serializable;
    @SuppressWarnings("serial")
    public class MyObject implements Serializable {
         private String mssg;
         private String clientID;
         private String clientName;
         public MyObject(String mssg, String clientID, String clientName) {
              this.mssg = mssg;
              this.clientID = clientID;
              this.clientName = clientName;
         //Generate getters and setters..
    }Continue on this, and when you get into problems etc post them. Also show with a small regular basis how far you have gotten with each class or it might be seen as you have lost intresst and then this thread is dead.
    EDIT: I should probably also say that Im not more than a java novice, at the verry most. So I cannot guarantee that I alone will be able to solve all the problems that might occure during this. But Im gonna try and help with the future problems that may(most likely will) occure atleast(Trying to reserve my self incase of misserable failiure from me in this attempt).
    Edited by: prigas on Jul 7, 2008 1:47 AM

  • Client Applet and EJB Server problem

    Hi,
    I developed a applet client that tries to connect to an EJB on the server side. The Applet runs okay in JDev3 but if I deploy it and test it outside the JDev tool I get an error. I tracked the problem to the following line of code:
    ic = new InitialContext(environment);
    Do I run into an applet security problem? If so what do i have to do to allow the applet to read/write to the local system?
    Thanks for any hints!
    Peter
    Error I get
    JAR cache enabled.
    Opening http://pete/gateway/clientmanagement.jar no proxy
    CacheHandler file name: C:\WINNT\Profiles\peter.000\Temporary Internet Files\Content.IE5\ALMN6PAZ\clientmanagement[1].jar
    Creating an initial context
    Opening http://pete/gateway/oracle/oas/container/nls/Version_en_US.class no proxy
    CacheHandler file name: null
    null

    Hi,
    I have still problems getting the client applet running. I tested it with the appletviewer and I modified the security.policy file. I allow the applet to almost everthing but i still get the following error:
    What do I do wrong? Do I really have to sign the jar file? Do I miss some stub classes?
    Thanks for any hints...
    Peter
    JAR cache disabled.
    Opening http://pete/Gateway/. no proxy
    Opening http://pete/Gateway/. no proxy
    Opening http://pete/Gateway/test/Client.class no proxy
    CacheHandler file name: C:\WINNT\Profiles\peter.000\Temporary Internet Files\Content.IE5\ALMN6PAZ\Client[1].class
    Opening http://pete/Gateway/test/Client$1.class no proxy
    CacheHandler file name: C:\WINNT\Profiles\peter.000\Temporary Internet Files\Content.IE5\ALMN6PAZ\Client$1[1].class
    Creating an initial context
    Looking for the EJB published as 'Gateway/GatewayProcessorRemote'
    Opening http://pete:80/_RMProxyURL_ no proxy
    Naming exception!
    [Root exception is org.omg.CORBA.NO_IMPLEMENT: minor code: 0 completed: No]javax.naming.ServiceUnavailableException
    at oracle.oas.jndi.oas.SecCosNamingContext.resolve(SecCosNamingContext.java:265)
    at oracle.oas.jndi.oas.BeanContext.lookup(BeanContext.java:328)
    at oracle.oas.jndi.oas.BeanInitialContext.resolve(BeanInitialContext.java:265)
    at oracle.oas.jndi.oas.BeanContext.lookup(BeanContext.java:328)
    at oracle.oas.jndi.oas.BeanInitialContext.lookup(BeanInitialContext.java:165)
    at oracle.oas.jndi.oas.WrapperContext.lookup(WrapperContext.java:78)
    at oracle.oas.jndi.oas.BeanContext.lookup(BeanContext.java:422)
    at javax.naming.InitialContext.lookup(InitialContext.java:288)
    at test.Client.initializeEJB(Client.java:104)
    at test.Client.startButton_actionPerformed(Client.java, Compiled Code)
    at test.Client$1.actionPerformed(Client.java:55)
    at java.awt.Button.processActionEvent(Button.java:308)
    at java.awt.Button.processEvent(Button.java:281)
    at java.awt.Component.dispatchEventImpl(Component.java, Compiled Code)
    at java.awt.Component.dispatchEvent(Component.java, Compiled Code)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java, Compiled Code)
    at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java, Compiled Code)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:92)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:83)
    null

  • Need help coding simple chat client/server

    I'm writing a simple chat server/client... its works fine when run on console.. but when i used Frames, AWT gui's.... it seems that the thread that is used to read the incoming message is suspended ... until i press the [send] button.. It seems to me that AWT consumes the time listening to any event.... and my thread is waiting... for the some AWT specific events to occur.....
    If your interested guys.. i'm willing to post the source code.. here.

    Try using the swing components. I think they are supposed to be more thread safe than awt. There is a tutorial for dealing with threads and swing:
    http://java.sun.com/tutorial/uiswing/overview/threads.html
    hopes this helps

  • Need help regarding Simple Data Client and Simple Data Server VIs

    Hi everyone.
    I have a simple objective. I just want to test the 2 example VIs, "Simple Data Client" and "Simple Data Server" between 2 computers. I just want to check whether is this working between the 2 computers.
    What I have done for now is that I changed the "address", from "localhost" in the "Simple Data Client.vi" to the IP address of the computer running the "Simple Data Server". I runned the "Simple Data Server" VI in one of the computers first followed by the "Simple Data Client" in the other computer. Nothing is received and the client just timed out.
    Can anyone please help me troubleshoot and tell me what are the possible problems for this? Are there any wires connections between 2 computers that I am missing or any other configurations I have to make before I can successfully do this?
    Thanks.
    Regards,
    Jonathan

    Hi Lee.P.
    I understand that. I was just feeling frustrated about the project not working. Sincere apologies from me.
    I was wrong about the error number. It is not Error 60. It is Error 59 - The network is down, unreachable, or has been reset.. Yes, I have tried changing the port numbers at the 2 computers when trying to send/receive.
    Could anything else be the problem?
    Regards,
    Jonathan  

  • A database error occurred. Source: Microsoft SQL Server Native Client 10.0 Code: 1205 occurred

    Hi
    i am getting these errors in sharepoint server event viewer, and when i see the sql server the log files disk is full memory only some mbs left out of 1 TB
    Log Name:      Application
    Source:        Microsoft-SharePoint Products-SharePoint Server Search
    Date:          7/12/2014 9:56:04 PM
    Event ID:      57
    Task Category: Search service
    Level:         Warning
    Keywords:     
    User:          XYZ\svc-mc-sps3eServsear
    Computer:      SPFIND01.xyz.gov.local
    Description:
    A database error occurred. Source: Microsoft SQL Server Native Client 10.0 Code: 1205 occurred 1 time(s) Description: Transaction (Process ID 193) was deadlocked on lock
    resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
    Context: Application 'XYZSP_SearchApp'
    Event Xml:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name="Microsoft-SharePoint Products-SharePoint Server Search" Guid="{C8263AFE-83A5-448C-878C-1E5F5D1C4252}" />
        <EventID>57</EventID>
        <Version>14</Version>
        <Level>3</Level>
        <Task>136</Task>
        <Opcode>0</Opcode>
        <Keywords>0x4000000000000000</Keywords>
        <TimeCreated SystemTime="2014-07-12T18:56:04.665684900Z" />
        <EventRecordID>225666</EventRecordID>
        <Correlation />
        <Execution ProcessID="3408" ThreadID="2932" />
        <Channel>Application</Channel>
        <Computer>SPFIND01.xyz.gov.local</Computer>
        <Security UserID="S-1-5-21-1537596049-1164153464-4201862467-47315" />
      </System>
      <EventData>
        <Data Name="string0">Microsoft SQL Server Native Client 10.0</Data>
        <Data Name="string1">1205</Data>
        <Data Name="string2">1</Data>
        <Data Name="string3">Transaction (Process ID 193) was deadlocked on lock resources with another process and has been chosen as the deadlock
    victim. Rerun the transaction.</Data>
        <Data Name="string4">
    Context: Application 'XYZSP_SearchApp'</Data>
      </EventData>
    </Event>
    A database error occurred. Source: Microsoft SQL Server Native Client 10.0 Code: 9002 occurred 1 time(s) Description: The transaction log for database 'tempdb' is full due to 'ACTIVE_TRANSACTION'.
    Context: Application 'XYZSP_SearchApp'
    adil

    If you've run out of disk space for your SQL databases then of course you'll get errors. Fix SQL then look to see if you're still getting errors.

Maybe you are looking for

  • Trees

    Creating a Tree from a single table (recursively), Makes Tree appear Correctly but with the problem that each node which is a parent of other nodes, reappear at the left side of the tree, making the tree appear with multiple roots, although it has on

  • ALG_RSA_SHA_PKCS1

    Hi guys, I have a question that seems to be rather critical, but I couldn't find any mention of it in the archive here: In the Java card API spec of Sigature class, ALG_RSA_SHA_PKCS1 is defined to expect the SHA hash, the algorithm will then pad it a

  • How to get muliple teaser images using assetset:getmultiplevalues?

    1. I have created a template called sample and Names it as sample.jsp 2. In the subTypes i selected a pageDefinition which i created alrady with the following page attributes      1.teaserImager 2.teaserText      Both attributes are Multiple 3. I the

  • BI Content Install Simulation Issue

    Hi, I'm installing the technical content in BI 7.x SP15.    When I simulate I get all kinds of errors in the infocube section saying InfoObject xxxx  is not available in active version.   But when I check the list of collected objects the infoobjects

  • Header Text Misalignment?

    I tried to search Discussions for this problem but it's hard for me to properly describe. In both the preview pane and a "full display" message window, the text comprising the displayed headers is misaligned. Next to the top line ("From:") the tops o