Help with MIDlets - TCP client server program

Hi I am new to using MIDlets, and I wanted to create a simple TCP client server program.. I found a tutorial in J2me forums and I am able to send a single message from server(PC) to client(Phonemulator) and from client to server. But I want to send a stream of messages to the server. Here is my program and I am stuck in the last step wher i want to send lot of messages to server. Here is my program, Could any one of u tell me how to do it? Or where am i going wrong in thsi pgm?
Code:
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeExcepti on;
public class SocketMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display display;
private Form addressForm;
private Form connectForm;
private Form displayForm;
private TextField serverName;
private TextField serverPort;
private StringItem messageLabel;
private StringItem errorLabel;
private Command okCommand;
private Command exitCommand;
private Command backCommand;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
display.setCurrent(addressForm);
protected void pauseApp() {
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
public void commandAction(Command cmd, Displayable d) {
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
display.setCurrent(connectForm);
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
notifyDestroyed();
public void run() {
InputStream is = null;
OutputStream os = null;
StreamConnection socket = null;
try {
String server = serverName.getString();
String port = serverPort.getString();
String name = "socket://" + server + ":" + port;
socket = (StreamConnection)Connector.open(name, Connector.READ_WRITE);
} catch (Exception ex) {
Alert alert = new Alert("Invalid Address",
"The supplied address is invalid\n" +
"Please correct it and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
try {
// Send a message to the server
String request = "Hello\n\n";
//StringBuffer b = new StringBuffer();
os = socket.openOutputStream();
//for (int i=0;i<10;i++)
os.write(request.getBytes());
os.close();
// Read the server's reply, up to a maximum
// of 128 bytes.
is = socket.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total<=5)
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0)
break;
total += count;
is.close();
String reply = new String(buf, 0, total);
messageLabel.setText(reply);
socket.close();
display.setCurrent(displayForm);
} catch (IOException ex) {
Alert alert = new Alert("I/O Error",
"An error occurred while communicating with the server.",
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
} finally {
// Close open streams and the socket
try {
if (is != null) {
is.close();
is = null;
} catch (IOException ex1) {
try {
if (os != null) {
os.close();
os = null;
} catch (IOException ex1) {
try {
if (socket != null) {
socket.close();
socket = null;
} catch (IOException ex1) {
private void initialize() {
display = Display.getDisplay(this);
// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);
// The address form
addressForm = new Form("Socket Client");
serverName = new TextField("Server name:", "", 256, TextField.ANY);
serverPort = new TextField("Server port:", "", 8, TextField.NUMERIC);
addressForm.append(serverName);
addressForm.append(serverPort);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);
// The connect form
connectForm = new Form("Connecting");
messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);
// The display form
displayForm = new Form("Server Reply");
messageLabel = new StringItem(null, null);
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);

Hello all,
I was wondering if someone found a solution to this..I would really appreciate it if u could post one...Thanks a lot..Cheerz

Similar Messages

  • HELP:USING CLIENT SERVER PROGRAM ON DIFF.MACHINES CONNECTED TO INTERNET?

    BELOW IS THE JAVA CODE FOR CLIENT & SERVER PROGRAM (TCP) USING SOCKET.
    I AM TRYING TO RUN CLIENT & SERVER PROGRAM ON 2 DIFFERENT MACHINES CONNECTED 2 INTERNET
    (1 RUNS SERVER.java & OTHER CLIENT.java).
    IS IT POSSIBLE WITH THE CODE WRITTEN BELOW?
    // Server.Java
    import java.net.*;
    import java.io.*;
    class Server {
    public static void main(String[] args) {
    boolean finished = false;
    try{
    ServerSocket listener = new ServerSocket(4444);
    while(!finished)
    {Socket to_client = listener.accept();
    OutputStream out = to_client.getOutputStream();
    PrintWriter pout = new PrintWriter(out, true);
    pout.println("Hello! this is server talking to you.");
    to_client.close();
    listener.close();
    }// end of try
    catch(Exception ie) {
    System.out.println(ie);
    //Client.Java
    import java.net.*;
    import java.io.*;
    class Client
    public static void main(String[] args)
    Socket client;
    String host="serverpcname";//host is assigned name of the server
    try
    {InetAddress adressen = InetAddress.getByName(host);
      client = new Socket(adressen,4444);
      BufferedReader scanf = new BufferedReader(new
      InputStreamReader(client.getInputStream()));
       String someString = scanf.readLine();
       System.out.println("From Server: "+someString);
      client.close();
    catch(Exception e)
    System.out.println(e);
    WHEN THE CODE IS EXECUTED(CLIENT.java ON 1 PC & SERVER.java on other) IT GIVES FOLLOWING EXCEPTIONS:
    java.net.UnknownHostException: serverpcname: serverpcname
    PLZ. GUIDE ME.
    THANKS IN ADVANCE.

    For a server to be accessible on the inetrnet it needs to have an externally visible IP address. For example, an address which starts with 192.168.1 is for internal use only can only be used by other machines on the same internal network. The server's firewall needs to allow the port you are using access and the client has to be able to lookup up the IP address either using the hosts file or via a DNS service. None of these things have anything to do with Java programming, so if you have any more questions I sugegst you try googling them or ask a forum which relates to these issues.
    The connection time out is due to the fact that there is no way to contact an inetrnal address over the inetrnet. The host unknwown means you haven't configured your PC to lookup that address. i.e. the host is unknown.

  • Client server programming

    Hi;
    I want to learn client server programming on using windows xp for the client and windows server 2003.
    I downloaded the 9.2 windows xp database version for the client . What do I need to download for the server? I see that there is a 32 and 64 bit version for the server.
    Thanks for your help!

    What I was asking is what should I install on the server
    the 32 or 64 bit version of oracle?
    I want to learn how to write client/server programs using Oracle.
    I have a network at home with one computer serving as the client and another has server 2003 on it.
    Again Thanks for your help!

  • About the communication issues in the client-server program

    About the communication issues in the client-server program
    Hi, I have some questions about the communication issues in a java project, which is basically the client and server architecture. In brief, the client, written in java, can be deployed anywhere, and in the following part, assume it is in the LAN (Local Area Network) which is connnected to the internet through the firewall and/or proxy, and the server, written in
    java too, simply provides the listening service on a port in a remote machine. And assume the server is connected to the internet directly so that the scenario can be simple to focus on the core questions.
    My questions are as follows:
    1 About the relationship between the communication port and protocol
    Generally, protocols at the application level like HTTP, FTP have their own default port, e.g., HTTP is corresponding to 80,
    FTP is to 25. But it is NOT necessary for the web server to provide the HTTP listening service at port 80, right? E.g, Tomcat provides the HTTP listening service at 8080. So it means the default relationship between the application protocl and their port is some routine, which is not necessary to follow, right?
    2 Assume a LAN connected to the internet through a proxy, which only allows HTTP protocol, then questions are:
    2.1 Does the proxy recognize the HTTP request from the client by the port number (carried in the request string)? For example, when the server provides the HTTP listening service at 80, then the request from the client will include the port number 80, then the proxy will parse such info and decide if or not the request can be out.
    2.2 Does the proxy recognize the HTTP request from the client by protocol (carried in the request string)? For example, the protocol used in the communicatin should be included in the request, then the proxy can parse it to make the decision.
    3 In java programm, if using the HTTP protcol, then on the client: the corresponding API is java.net.URLConnection, right?
    If using the TCP protocol directly, then on the client:the corresponding API is java.net.Socket, right? In both cases, the server side use the same API, java.net.ServerSocket?
    Is it correct to say that the communication by Socket is faster than URLConnection?
    4 Take MSN messenger for example, which protocol does it use? Since proxy configure is only the possible option, so I guess generally the TCP protocol is used directly so that the better perfomrance can be achieved, right?
    5 Given 3 computers within the same LAN, can the client, proxy, server environment above be correctly simulated? If so, can
    you recommend me some typical proxy program so that I can install it to configure such an enviroment to perform some test?
    6 I guess there should be some software to find out which port number a given program/process is going through to connect to
    the remote machine, and which port number a given program/process is listening on? Also, what protocl is used in the given
    communication.
    7 Finally, regarding each of the above questions, it will be highly appreciated that if you can recommed some references,
    tutorials, books etc. In summary, what I care about is how to enable the java client behind the proxy and firewall to
    communicate with the remote server without problems, so if you know some good tutorials plz let me know and thx in advance!
    Finally, thanks for your attention so such long questions =).

    FTP is to 25. But it is NOT necessary for the web
    server to provide the HTTP listening service at port
    80, right? E.g, Tomcat provides the HTTP listening
    service at 8080. So it means the default relationship
    between the application protocl and their port is
    some routine, which is not necessary to follow,
    right?Not sure what you're saying here.
    There must be a server listening on some port. The client must know what port that is. If you open the connection using the Socket class, you'll explicitly specify the port. If you use some higher level class like URLConnection or something in the commons Net package, there's probably a default port that will be used if you don't explicitly specify another.
    There's no way for the client to know that the HTTP request will go to port 80 instead of port 8080. If you think the the client contacts the server without explicitly naming a port, and then asks the server "get me your HTTP server", and the port is determined from that, you're mistaken.
    Not sure if you're thinking that, but it sounded like you might be.
    2 Assume a LAN connected to the internet through
    a proxy, which only allows HTTP protocol, then
    questions are:
    2.1 Does the proxy recognize the HTTP request
    from the client by the port number (carried in the
    request string)? For example, when the server
    provides the HTTP listening service at 80, then the
    request from the client will include the port number
    80, then the proxy will parse such info and decide if
    or not the request can be out. I'm not sure, but I think most proxies and firewalls are configured by ports. I thought I'd heard of more sophisticated, higher-level ones that could understand the content to some degree, but I don't know anything about those.
    3 In java programm, if using the HTTP protcol,
    then on the client: the corresponding API is
    java.net.URLConnection, right?That's one way.
    You might want to look into this:
    http://jakarta.apache.org/commons/httpclient/
    If using the TCP protocol directly, then on the
    client:the corresponding API is java.net.Socket,
    right? In both cases, the server side use the same
    API, java.net.ServerSocket? A Java client will user Socket, and a Java server will use ServerSocket and Socket.
    Is it correct to say that the communication by Socket
    is faster than URLConnection?Probably not.

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Client Server program using Applets for client

    Creating a client server program using Applets for the clients.
    Having problems distrubting the message from client to client
    using ObjectOutputStreams/ObjectInputSteams.
    I can connect each client to simple server and respond with by writting
    the i/o stream of each client but unable to communicate from client to client. If any one out there has in tips of creating a class of objectOutputStreams that holds a array of ObjectOutputStreams and then broadcasts the message to every client, it would be much appreciated
    Thanks.

    Cheers poop for your reply
    I never explained the problem properly. What it is I am trying to set up a Client Server program using Applets as the clients GUI. The problem is broadcasting the message to multiply client connnection(s).
    Below is code, each client can connect and send message to the server. The problems is broadcasting the message to every client connection. The every client can input a message but only the last connected client can receive the message?????? Thanks in advance..
    /*this my server class */
    import java.io.*;
    import java.net.*;
    public class Server extends JFrame
    private static final int ServerPort=8080;
    private static final int MaxClients=10;
    private ObjectOutputStream output=null;
    private ObjectInputStream input=null;
    private BroadCastMessage broadcastMessage;
    public void runServer()          
    BroadCastMessage broadcastMessage= new BroadCastMessage();
    try
    {  //connect to server
    ServerSocket s = new ServerSocket(ServerPort,MaxClients);
         //listen to port 5000 for new connections
         ///max is 25
         System.out.println("Server listening on port "+ServerPort);
    while (state.isProgramRunning())
         try
         /// sGUI.waitForConnection();//new line
         s.setSoTimeout(100);
         //enable times in server-socket
         while (true)     
         Socket incoming = s.accept();
         //wait and accept connnections from serverSocket
         //instance of the class,pases the new connection and message
         //spawn as a thread
         SocketConnection connection=new SocketConnection(incoming,broadcastMessage);
         Thread a = new Thread(connection); a.start();
         System.out.println(state.getConnectionCount()+"Connection received from :"+incoming.getInetAddress());
         catch(InterruptedIOException x){}
    while (state.getConnectionCount()>0);
    System.exit(0);
    }catch (IOException e){}
    public static void main(String[] args)
    Server s =new Server();
         s.runServer();
    /*this is my socket connection thread*/
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    public class SocketConnection implements Runnable
    private ObjectOutputStream out;
    private ObjectOutputStream output=null;
    private ObjectInputStream input=null;
    private BroadCastMessage passOnMessage;
    private Socket theConnection=null;
    private String Inmessage="";
    private int Ocount;
    public SocketConnection(Socket caller,BroadCastMessage broadcastMessage,Ocount)
    theConnection =caller;///(5000,n)
    Ocount=ncount;
    passOnMessage=broadcastMessage;
    public void run()
    try
    getStreams();
    processConnection();
    catch(Exception e)
    {String clientDetails=("connection from IP Address: "+theConnection.getInetAddress());}
    private synchronized void getStreams() throws IOException
    { //get streams to send and receive data
    //set up output buffer to send header information
    ///Ocount++;
    //create new objectoutputstream
    output=passOnMessage.getOutputObject(output,theConnection,Ocount);
    ///flush output buffer to send header info.
    Ocount++;
    //set up input stream for objects
    input =new ObjectInputStream(
    theConnection.getInputStream());
    System.out.print("\nGot I/O streams\n");
    private synchronized void processConnection()throws IOException
    //process connection with client
    String Outmessage =" count : "+status.getConnectionCount();
    //send connection successful message to client
         Outmessage=Outmessage+"SERVER>>>Connection successful";
         output.writeObject(Outmessage);
    output.flush();
    do ///process messages sent from client
         try
         Inmessage = (String) input.readObject();
         System.out.println(Inmessage);
         /* //while the connection is open each line
         that is passed from the client to the server
         is read in and is displayed*/
         messageDetails.setMessage(Inmessage);
         String CurrentMessage=messageDetails.getMessage();
         //output.writeObject(CurrentMessage);
         // output.flush();
         passOnMessage.FloodMessage(CurrentMessage);
         //sending out the message
    catch(ClassNotFoundException classNotFoundException){}
    }while (!Outmessage.equals("CLIENT>>>TERMINATE"));
    /*this my attempt at broadcasting the message to all clients
    my thinking was that you could create a array of objectoutputstreams
    which in turn could be broadcasted(bit confussed here)*/
    import java.io.*;
    import java.net.*;
    public class BroadCastMessage /// implements Runnable
    private int count;
    private String Inmessage="";
    private ObjectOutputStream temp=null;
    private ObjectOutputStream[] output = new ObjectOutputStream [12];
    //temp level of array of objects
    public BroadCastMessage()
    count=0;
    public synchronized void FloodMessage(String message) throws IOException
    System.out.print(count);
         for(int i=0;i<count+1;i++)
         try
    {  System.out.print(count);
         output[count].writeObject(message);
         output[count].flush();
         catch(IOException ioException)
    {ioException.printStackTrace();}
         notifyAll();
    public ObjectOutputStream getOutputObject(ObjectOutputStream out,Socket caller,int Ocount)
    try
    { temp = new ObjectOutputStream(caller.getOutputStream());
         AddObjectOutputStream(temp,Ocount);
    ////FloodMessage();
         catch(IOException ioException)
    {ioException.printStackTrace();}
    return temp;     
    public void AddObjectOutputStream(ObjectOutputStream out,int Ocount)
    { ///add new object to array
    count=Ocount;
    output[count]=out;
    System.out.print("\nthe number of output streams : "+count+"\n");
    }

  • TCP Client - Server Prog.

    Hi All,
    I have posted TCP client- server prog. I have trouble in client code. When i'm running the server code on some port and the running the client code on the same port, then client is sending message to server(in this case integers with space like 12 22 23) , the server is receiving the message and adding the sum and sending the sum to client, but when i'm trying to read the stream from server(i.e the sum), i'm getting nothing.........
    please run the code and check.......u can understand well....
    please reply me as soon as possible.
    Thanks
    import java.io.*;
    import java.net.*;
    class TCPAdditionClient
         public static void main(String args[]) throws Exception
         {   Character ans = null;
              String hostname="localhost";
              String sentence;
              String result;
              int port=0;
              if (args.length > 0) {
              try {
              port = Integer.parseInt(args[0]);
              } catch (NumberFormatException e) {
              System.err.println("Argument must be an integer");
              System.exit(1);
              Socket clientSocket = new Socket(hostname,port);
              do
                   System.out.println("Enter the number of integers....");
                   BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
                   sentence = fromUser.readLine();
                   DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                   //System.in.read();
                   outToServer.writeBytes(sentence + '\n');
                   System.out.println("server sends message");
                   BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   System.out.println(fromServer);
                   result = fromServer.readLine();
                   System.out.println("from Server" + result);
                   System.out.println("Do u want to continue y/n");
              }while(! ans.equals("n"));
              clientSocket.close();
    import java.io.*;
    import java.util.*;
    import java.net.*;
    class TCPAdditionServer
         public static void main(String args[]) throws Exception
              String clientSentence;
              int port=0;
              if (args.length > 0) {
              try {
              port = Integer.parseInt(args[0]);
              } catch (NumberFormatException e) {
              System.err.println("Argument must be an integer");
              System.exit(1);
              ServerSocket welcomeSocket = new ServerSocket(port);
              while(true)
                   int sum = 0,total_sum = 0;
                   Socket connectionSocket = welcomeSocket.accept();
                   BufferedReader fromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                   DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                   clientSentence = fromClient.readLine();
                   System.out.println(clientSentence);
                   String[] result = clientSentence.split(" ");
                   for (int x=0; x<result.length; x++)
                        sum = Integer.parseInt(result[x]);
                        total_sum = sum + total_sum;
                        System.out.println(total_sum);
                   String sendData = "from the server" + "sum :" + total_sum;
                   System.out.println(sendData);
                   outToClient.writeBytes(sendData);
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    can u explain it http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Design Pattern for multithreaded client server program

    I asked this question in another post, but with other stuff, so I'll distill this one.
    I am creating a multi-threaded client server program (just for learning - a chat program at this point). I built the server and client in swing, and I'm wondering what the best design pattern is for this setup. Right now all the swing stuff is in the MyServer class. In that class I have a loop accepting client connections to the serverSocket and creating a new MyServerThread (threaded client connection).
    The problem is that all the work of creating input streams, interacting with the server, all that stuff is done in the MyServerThread class, but I want that text to be written up to the Swing objects - which is in the MyServer class. So right now in the MyServerThread class I pass the MyServer object into it, but I'm not sure if that is really the most robust thing to do. Does anybody have any suggestions as to how this should be done. If somebody has an article they'd like to point to I'll check it out too. But if it's just the run-of-the-mill multithreaded client-server article, I've read alot and most don't specifically address my question.

    Thanks for the reply Kaj, and I think I'll keep my design for now, since it's just quick and dirty. I've read the MVC concept a while ago and I'll revisit it again when I get more serious. But I have a question, why should I be using a callback interface, why an interface at all? And then make MyServer implement that interface...why not just pass MyServer to the thread object? Or is there something down the line that I did not forsee?

  • Can we run oracle Forms 5 Application with 10G in Client/Server?

    Hi All,
    Can we run oracle Forms 5 Application with 10G in Client/Server
    Mode?
    Regards
    Gaurav

    In theory you can run it 2 tier - which means that you have the client (the machine the user is sitting at) being the same machine in which the forms application server is running. So yes. But specifically, we don't support a client server runtime anymore. 6i was the last version.
    With 10g you will be running through a browser.
    Regards
    grant

  • Client/server program: Urgent, pls help!!

    I am new to Java, particularly Networking in Java, while writing client/server application I have got completely strucked now. Can any one give me an idea where I am wrong?
    I am writing a simple client server application in Java using Socket and ServerSocket classes as a part of my course work. Through client I am just establishing connection with server, getting user inputs/commands, sending the same input to server (server will capitalize this input and return it back to client), receiving and displaying server�s response.
    The connection is established fine. Even it is accepting users input well but I am getting runtime NullPointerException while trying to send it to server. Here is the working of my client command window.
    C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>javac TClient.java
    C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>java TClient
    Enter the message
    hello
    Exception in thread "main" java.lang.NullPointerException
    at TClient.Send_Message(TClient.java:46)
    at TClient.main(TClient.java:76)
    C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>
    As soon as I get this exception the connection with server is lost and I get this in server command window.
    C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>javac TCPServer.java
    C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>java TCPServer
    Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java
    :2150)
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream
    .java:2163)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputS
    tream.java:2631)
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:734
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:253)
    at TCPServer.main(TCPServer.java:17)
    C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>
    Here is my code for server (TCPServer.java)
    import java.io.*;
    import java.net.*;
    class TCPServer {
      public static void main(String argv[]) throws Exception
          String clientSentence;
          String capitalizedSentence;
          ServerSocket welcomeSocket = new ServerSocket(80);
          while(true) {
                       Socket connectionSocket = welcomeSocket.accept();
               ObjectInputStream inFromClient =  new ObjectInputStream(connectionSocket.getInputStream());
               ObjectOutputStream  outToClient =
                 new ObjectOutputStream(connectionSocket.getOutputStream());
               clientSentence = (String ) inFromClient.readObject();
               capitalizedSentence = clientSentence.toUpperCase() + '\n';
               outToClient.writeObject(capitalizedSentence);
    And this is for Client (TClient.java)
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class TClient {
         private ObjectOutputStream  server_output;
                private ObjectInputStream server_input;
         private Socket client;
         private void server_connect() throws IOException
              client = new Socket(InetAddress.getLocalHost(), 80);
         private void getstreams() throws IOException
          server_output = new ObjectOutputStream (client.getOutputStream());
          server_output.flush();     
             server_input = new ObjectInputStream(client.getInputStream());
         private String get_cmd_frm_usr() throws IOException
              BufferedReader inFromUser =
                         new BufferedReader(new InputStreamReader(System.in));
              String sentence;
              System.out.println("Enter the message");
              sentence = inFromUser.readLine();
              /*StringTokenizer st = new StringTokenizer(sentence);
                   while (st.hasMoreTokens()) //separating n printing words of inputted sentence
                       System.out.println(st.nextToken());
         return(sentence);
         private void Send_Message(String msg) throws IOException
              //System.out.println("within send_message method :"+ msg);
              server_output.writeObject( msg );
              server_output.flush();
         private void recieve_n_disp_mess() throws Exception
         String modifiedSentence;
         modifiedSentence = ( String ) server_input.readObject();
         System.out.println("\n\n  by SERVER: " +      modifiedSentence);
            private void close_connection() throws IOException
              client.close();
         public static void main(String args[]) throws Exception
              TClient client = new TClient();
             try{
              client.server_connect();
              String command=client.get_cmd_frm_usr();
              //System.out.println("this is returned from input method n ready to sent to server soon: "+ command);
              client.Send_Message(command);
              client.recieve_n_disp_mess();
              client.close_connection();
                   } catch(EOFException eofException) {}
              catch (IOException ioException) {}          

    you never initialized the server_output and the server_input vriables...
    I see you have the getstreams() function which should initialize them but you never call it...
    so untill you will call it those variables will stay null.
    I can also see you do not implement constructors, its much easier just to implement these instead of functions initializing variables...
    Hope it will help
    private void getstreams() throws IOException
    server_output = new ObjectOutputStream
    (client.getOutputStream());
    server_output.flush();
    server_input = new
    ObjectInputStream(client.getInputStream());
    public static void main(String args[]) throws
    Exception
    TClient client = new TClient();
    try{
    client.server_connect();
    String command=client.get_cmd_frm_usr();
    //System.out.println("this is returned from input method n ready to sent to server soon: "+ command);
    client.Send_Message(command);
    client.recieve_n_disp_mess();
    client.close_connection();
    } catch(EOFException eofException) {}
    catch (IOException ioException) {}

  • Help with my FTP client program

    Hello All,
    I am trying to modify a client FTP program to get a grasp on network programming. However when I try to connect to the host I get an error of Anonyymous login. What am I doing wrong? Below is the FTPclass program that I found on the net. How do resolve this issue? Thanks!!
          * Connects to the given FTP host on port 21, the default FTP port.
    //     public boolean connect(String host, int port, String userName, String passWord) throws UnknownHostException,
    //               IOException {
    //          return connect(host, 21, userName, passWord);
          * Connects to the given FTP host on the given port.
         public boolean connect(String host, int port, String userName, String passWord) throws UnknownHostException,
                   IOException {
              connectionSocket = new Socket(host, port);
              outputStream = new PrintStream(connectionSocket.getOutputStream());
              inputStream = new BufferedReader(new InputStreamReader(connectionSocket
                        .getInputStream()));
              if (!isPositiveCompleteResponse(getServerReply())) {
                   disconnect();
                   return false;
              return true;
          * Disconnects from the host to which we are currently connected.
         public void disconnect() {
              if (outputStream != null) {
                   try {
                        if (loggedIn) {
                             logout();
                        outputStream.close();
                        inputStream.close();
                        connectionSocket.close();
                   } catch (IOException e) {
                   outputStream = null;
                   inputStream = null;
                   connectionSocket = null;
          * Wrapper for the commands <code>user [username]</code> and <code>pass
          * [password]</code>.
         public boolean login(String username, String password) throws IOException {
              int response = executeCommand("user " + username);
              if (!isPositiveIntermediateResponse(response))
                   return false;
              response = executeCommand("pass " + password);
              loggedIn = isPositiveCompleteResponse(response);
              return loggedIn;
          * Added by Julian: Logout before you disconnect (this is good form).
         public boolean logout() throws IOException {
              int response = executeCommand("quit");
              loggedIn = !isPositiveCompleteResponse(response);
              return !loggedIn;
          * Wrapper for the command <code>cwd [directory]</code>.
         public boolean changeDirectory(String directory) throws IOException {
              int response = executeCommand("cwd " + directory);
              return isPositiveCompleteResponse(response);
          * Wrapper for the commands <code>rnfr [oldName]</code> and <code>rnto
          * [newName]</code>.
         public boolean renameFile(String oldName, String newName)
                   throws IOException {
              int response = executeCommand("rnfr " + oldName);
              if (!isPositiveIntermediateResponse(response))
                   return false;
              response = executeCommand("rnto " + newName);
              return isPositiveCompleteResponse(response);
         /**Here is the code to test the client program
    lass verifyFTP {
         public static void main(String[] args) {
              String serverName;
              String portNumber;
              int port = 21;
              FTPConnection ftp = null;
              try {
                   if (args.length == 0) {
                        serverName = getStringFromUser("Enter the server you would like to connect to: ");
                        if (serverName.length() == 0) {
                             return;
                        }//end if
                   } else {
                        serverName = args[0];
                   }//end else
                   String userName = "";
                   String passWord = "";
                   // set the FTPConnection parameter to true if you want to
                   // see debug output in your console window
                   ftp = new FTPConnection(true);
                   System.out.println("Attempting to connect to " + serverName);
                   ftp.connect(serverName, port, userName, passWord);
                   if(ftp.login("", "")){
                        System.out.println("Successfully logged in!");
                        System.out.println("System type is: " + ftp.getSystemType());
                        System.out.println("Current directory is: "
                                  + ftp.getCurrentDirectory());
                        String files = ftp.listFiles();
                        // private function that gets console input from the user
         private static String getStringFromUser(String prompt) throws IOException {
              System.out.print(prompt);
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              return br.readLine();

    You should print out exactly what you are sending and what you are recieving via the socket. You do this just before you send it and when you receive it (you do not modify it in any way first.)
    You should also use an existing FTP client to log into your server. Presumably it is successful. Then you can use ethereal (free software google it) to examine exactly what the FTP client sends versus what you are sending. You will probably find that it is sending a different command than what you are.

  • TCP client server sample

    All,
    This may not really be a LabWindows/CVI question but I'm really stuck on what should be easy to
    solve. The brain trust here on the forums has always been helpful so I'll try to explain.
    The project:
    Get LabWindows/CVI code talking to a muRata SN8200 embedded WiFi module.
    The setup:
    (running Labwindows/CVI 2009)
    Computer 1 -- (with a wireless NiC) running simple demo TCP server program provided by muRata.
    Computer 2 -- USB connection (virtual COM port) with simple program (also provided by muRata) that talks to the SN8200 embedded WiFi module.  This code along with the module creates a simple TCP client.
    Whats working:
    I can successfuly get the Computer 2 client connected to and talking to the Computer 1 server. (using the muRata supplied code)
    I can also run the LabWindows/CVI sample code from (\CVI2009\samples\tcp), server on computer 1 & client on computer 2 and they talk with no problems.
    (I'm using the same IP addresses and port numbers in all cases)
    Whats NOT working:
    Run the CVI server program on computer 1.
    I cannot get the muRata client program  to connect to the CVI server.
    I also tried get the CVI client program to connect to the muRata server.  No luck that way either. The CVI client sample program trys connect, and this function call:
    ConnectToTCPServer (&g_hconversation, portNum, tempBuf, ClientTCPCB, NULL, 5000 );
    returns with a timeout error code (-11).
    What I need:
    Some ideas on how to get this working.
    Is there something unique about the LabWindows/CVI sample client/server demo code that would make them incompatible with the muRata code?
    Can you think of some ways I can debug this further?  I feel like I'm kind of running blind.
    What else can I look at?
    For those that have read this far, thanks much and any ideas or comments will be appreciated,
    Kirk

    Humphrey,
    First,
    I just figured out what the problem is:
    When I was trying to use the CVI sample server I was entering the wrong port number.
    The reason I entered the wrong port was because the hard-coded port number in the muRata demo code was displayed in hex as 0x9069. ( I converted this to decimal and entered it into the CVI sample server code) The correct port number was 0x6990.  (upper and lower bytes swapped)  Arrgh!
    I found the problem by using the netstat command line utility to display the connections and noted that the port being used was not 0x9069.  It is really a problem with the muRata eval kit demo code.
    Second,
    Humphrey you are right about the CVI sample code not handling all the muRata commands for the client end of the connection that communicates with the SN8200 module.  For my test I was using the muRata code for that "end".
    The server end is simple and the CVI sample is adequate and is now working.
    Thank you to all who took the time to browse my questions,
    Kirk

  • TCP client server

    hi,
    how do i do this:
    Create a Server Program in TCP
    Create a file with some data.
    Create a Client Program in TCP
    Establish a connection with the server
    On establishment, the server should read the data from the file and write onto the socket of the client.
    The client has to read the data from the socket and write onto a different file.

    hi,
    this is the server code that i have.
    import java.io.*;
    import java.net.*;
    public class fileServer {
    public fileServer() {
    int i=1;
    try {
    ServerSocket s = new ServerSocket(5000);
    System.out.println("Server Started...");
    Socket incoming = s.accept();
    Thread t = new ThreadedServer(incoming, i);
    i++;
    t.start();
    }catch(Exception e){
    System.out.println("Error: "+e);
    public static void main(String args[]){
    new fileServer();
    class ThreadedServer extends Thread{
    int n;
    Socket fileSocket;
    int count;
    public ThreadedServer(Socket i, int c){
    fileSocket = i;
    count = c;
    public void run(){
    BufferedReader buffRead = null;
    OutputStream os;
    try{
    File f = new File("file1.txt");
    FileInputStream fis = new FileInputStream(f);
    os = fileSocket.getOutputStream();
    int buffSize = 4096;
    byte[] buff = new byte[buffSize];
    int count = 0;
    while((count = fis.read(buff))>= 0) {
    os.write(buff,0,(int)count);
    System.out.println(os);
    fis.close();
    os.close();
    }catch(IOException ioe) {
    System.out.println("this is a IOException"+ioe.getMessage());
    This is the client code that i have:
    import java.io.*;
    import java.net.*;
    public class fileClient{
    public static void main(String args[]){
    Socket clientSocket;
    PrintStream out = null;
    BufferedReader in = null;
    try{
    clientSocket = new Socket("10.45.2.34",5000);
    System.out.println("connection established");
    out = new PrintStream(clientSocket.getOutputStream());
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String text = in.readLine();
    System.out.println(text);
    in.close();
    out.close();
    }catch (UnknownHostException e){
    System.err.println("unidentified hostname");
    System.exit(1);
    }catch(IOException ioe) {
    System.err.println("couldnt get I/O");
    System.exit(1);
    The above code works fine,but the final step i.e the client has to read the data from the socket and write onto a different file is not performed.
    So how do i proceed from here.

  • Multiple Clients in Client/Server Program

    I'm currently trying to make a small Client/Server application that will mimic a very basic chat room program. The basic idea is that the Server side of the program is started and multiple Client programs can connect and communicate with each other. However, I'm having a few problems at the moment, mostly with figuring out how it can work.
    Firstly, I can communicate one to one with the server and the client as the client socket is stored in a variable. However, to make it possible to allow multiple connections I've used a thread for each new connection but I'm not sure how I can broadcast messages to every connection. Would it be safe enough to store each client socket in a list and then communicate that way? Not sure what will happen when the client disconnects though it seems to be an issue.
    I'm also not sure how every message can be broadcasted to every single connections to the server. The server program can send a message to every client but the clients message at the moment only goes to the server. Anyway here's a bit of my code so far:
    SwingWorker<Socket, Void> worker = new SwingWorker<Socket, Void>() {
            protected Socket doInBackground() throws Exception {
                // Client socket
                try {
                    while (!stopRequested) {
                        clientSocket = serverSocket.accept();
                        // Stop requested is checked twice because the accept() method
                        // waits for a connection
                        if (!stopRequested) {
                            HostFrame.getFeedbackTextArea().append("New Connection Found");
                            Thread clientThread = new HandlerThread(clientSocket);
                            clientThread.start();
                        else {
                            serverSocket.close();
                            clientSocket.close();
                catch (Exception e) {
                    HostFrame.getFeedbackTextArea().append("Failed to Connect with Client");
                    System.out.println(e.getMessage());
                return clientSocket;
        };The SwingWorker is used so that the GUI doesn't freeze when the server tries to find a connection. At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client. Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets. Any help would be much appreciated

    clientSocket = serverSocket.accept();'clientSocket' should be a local variable here.
    else {
    serverSocket.close();
    clientSocket.close();You shouldn't close 'clientSocket here'. All you're accomplishing is closing the most recently accepted client socket. What about the others? Generally speaking you should let the client-handling threads take care of their own sockets completely.
    return clientSocket;This return statement is meaningless. You may as well return null. SwingWorker doesn't care. Don't just return something because you've got it lying around. In this case you shouldn't have it lying around.
    At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client.That is exactly what you have to do to handle more than one client. Once you fix it as per above.
    Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets.You probably need to keep a Map of client sockets accepted, keyed by some client identifier.

  • Client/server program validation - is it possible?

    I've been mulling over this problem for a few days, and am starting to wonder if it's theoretically possible to find a solution. I'm not looking for specific code, this probably won't even be implemented in Java, I'm just wondering if there is a theoretical program model that would work in this situation.
    The short version:
    Validate the data generated by a client program, without knowing the original data.
    The long version:
    This is a "profiling" system for a MMOG (Massively Multiplayer Online Game). The MMOG is an internet based client/server graphical program where each client connects to the server and they interact with each other and the virtual world. They pay a monthly fee for access to the game. My program is not affiliated with the MMOG or its makers. I have no connections inside the company and cannot expect any cooperation from them.
    The "profiling" system is also a client/server model. The client program runs in the background while the MMOG client is active. It accesses the memory of the MMOG client to retrieve information about the player's character. Then, possibly on request or maybe immediately, it sends the character data to our server.
    What I want to validate is that the character data being sent is unmodified and actually comes from the MMOG program.
    I can reasonably expect that with mild encryption and some sort of checksum or digest, the vast majority of problems can be avoided. However, I am not sure it's possible to completely secure the system.
    I assume that the user has access to and knowledge of the profiler client and the MMOG client, their assembly code, and the ability to modify them or create new programs, leveraging that knowledge. I also assume that the user does not have access to or knowledge of either of the server applications - the MMOG server or mine.
    In a worst-case scenario, there are several ways they could circumvent any security I have yet been able to think of. For instance, they could set up a fake MMOG client that had the data they wanted in memory, and let the profiler access that instead of the real thing. Or, they could rewrite the profiler to use the data they wanted and still encrypt it using whatever format I had specified.
    I have been considering using some kind of buffer overflow vulnerability or remote execution technique that would allow me to run specific parts of the client program on command, or get information by request, something that could not be anticipated prior to execution and thus could not be faked. But this seems not only insecure for the client but also not quite solid enough, depending on how it was implemented.
    Perhaps a series of apparently random validation codes, where the client does not know which one actually is doing the validation, so it must honor them all. Again, this is very conceptual and I'm sure that I'm not explaining them very well. I'm open to ideas.
    If I don't come up with anything better, I would consider relying on human error and the fact that the user will not know, at first, the relevance of some of the data being passed between client and server. In this case, I would include some kind of "security handshake" that looks like garbage to the client but actually is validated on the server end. A modified program or data file would result in an invalid handshake, alerting the server (and me) that this client was a potential problem. The client would have no idea anything had gone wrong, because they would not know what data the server was expecting to receive.
    I hope I have not confused anyone too much. I know I've confused myself....

    Yes, that is the general model for all MMOGs these days - no data that can actually affect the game is safe if loaded from the client's computer. All character and world data is sent from server to client and stored in memory. Any information that is saved to the client's computer is for reference only and not used by the game engine to determine the results of actions/events etc.
    My program accesses the MMOG client's memory while the game is running, and takes the character information from there. It does not have direct access to the MMOG server, and does not attempt to modify the data or the memory. Instead, it just encrypts it and sends it to our server, where the information is loaded into a database.
    The security issue comes into play because our database is used for ranking purposes, and if someone were to hack my program, they could send invalid data to our servers and affect the rankings unfairly.
    I'm just trying to think of a way to prevent that from happening.

Maybe you are looking for