Begging for help. SSLSocket client/server

Hello Everyone,
At my wits end and behind my project plan. I need to secure my server.
I have generated a keystore
Exported certificate into CER file
Imported this certicate into the JAVA_HOME/lib/security/cacerts file.
I have my JBoss secured on port 8443.
Here is m client code
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public
class EchoClient
public
static
void
main(String [] arstring)
try
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket)sslsocketfactory.createSocket("172.16.220.178:8443", 9999);
InputStream inputstream = System.in;
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
OutputStream outputstream = sslsocket.getOutputStream();
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
String string = null;
while ((string = bufferedreader.readLine()) != null)
bufferedwriter.write(string + '\n');
bufferedwriter.flush();
catch (Exception exception)
exception.printStackTrace();
and here is my server code
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public
class EchoClient
public
static
void
main(String [] arstring)
try
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket)sslsocketfactory.createSocket("172.16.220.178:8443", 9999);
InputStream inputstream = System.in;
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
OutputStream outputstream = sslsocket.getOutputStream();
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
String string = null;
while ((string = bufferedreader.readLine()) != null)
bufferedwriter.write(string + '\n');
bufferedwriter.flush();
catch (Exception exception)
exception.printStackTrace();
How can I get this client/server talking using my own keystore. ????
I only need my server to be secured. I dont need any client authentication or anything. I just need my client to connect using Sockets to a secure server.
Thanks.
Desperate Joyce

Ok, you can't secure a server, you can only sercure the connection between them. That means either the client needs who it is talking to or the server needs to know who it is talking to. You can have a ssl connection where nobody knows who they are talking to as well if you want. I'll go through it for server authentication by client. If you need it the other way around the same principle holds. Give me an hour and I'll put up the code for a connection without auth.
Ok, if you need to authenticate the server.
In the client you will need to have a keystore for trusted certificates (i.e. cacerts)
You will need a trustmanager to decide whether or not to trust the server.
And using both of these you need to create as ssl context.
On the server, you will need a keystore containing its X509 certificates
A keymanager to manage these certificate and again an SSL context.
Then start the handshake. The client will connect to the server using an SSL Socket.
On the starthandshake() method, the server will sent the client its X509 certificates from its
keystore. The clients trust manager will then try to create a certificate chain from these certificates
back to one of its trusted certificates (stored in its trusted keystore).
Client should look a little like this:
SSLContext ctx;
     TrustManagerFactory tmf;
     KeyStore ks;
     char[] passphrase = "passphrase".toCharArray();
     System.out.println("set up context, keystore and trustManagerFactory");
     ctx = SSLContext.getInstance("SSL");
     tmf = TrustManagerFactory.getInstance("SunX509");
     ks = KeyStore.getInstance("JKS");
                     System.out.println("set context to ssl, tmf to X509 and keystore to JKS");
     ks.load(new FileInputStream("testkeys"), passphrase);
     System.out.println("loading testkeys using passphrase");
     tmf.init(ks);
     System.out.println("initialise keystore using passphrase");
     ctx.init(null, tmf.getTrustManagers(), null);
     System.out.println("initialise the key manager");
     SSLSocketFactory factory = ctx.getSocketFactory();
     System.out.println("got socket factory, now trying to create socket");
                      SSLSocket socket = (SSLSocket)factory.createSocket(serverAddress, port);
                     System.out.println("starting handshake");
     socket.addHandshakeCompletedListener(new HandshakeCompletedListener()
                           public void     handshakeCompleted(HandshakeCompletedEvent event)
               System.out.println("Handshake finished!");
               System.out.println("\t CipherSuite:" +
               event.getCipherSuite());
               System.out.println("\t SessionId " +
               event.getSession());
               System.out.println("\t PeerHost " +
               event.getSession().getPeerHost());
     socket.startHandshake();
     System.out.println("SSL Socket Connected");
     catch (Exception e)
          System.out.println("error along the way somewhere :" + e.getMessage());
                          e.printStackTrace();
    }The Server will look a little like this:
//=================================================================================
SSLServerSocketFactory ssf = null;
try
                     SSLContext ctx;
     KeyManagerFactory kmf;
     KeyStore ks;
     char[] passphrase = "passphrase".toCharArray();
                     System.out.println("set up context, keystore and keymanagerfactory");
     ctx = SSLContext.getInstance("SSL");
     kmf = KeyManagerFactory.getInstance("SunX509");
     ks = KeyStore.getInstance("JKS");
     System.out.println("set context to ssl, kmf to X509 and keystore to JKS");
     ks.load(new FileInputStream("testkeys"), passphrase);
     System.out.println("loading testkeys using passphrase");
     kmf.init(ks, passphrase);
     System.out.println("initialise keystore using passphrase");
     ctx.init(kmf.getKeyManagers(), null, null);
     System.out.println("initialise the key manager");
     ssf = ctx.getServerSocketFactory();
     System.out.println("got the server socket factory for that context");
catch (Exception ex)
     System.out.println("Error along the way somewhere : " + ex.getMessage());
     ex.printStackTrace();
try
     SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(port);
     System.out.println("created ssl server socket for port " + port);
     myServer serve = new myServer(ss);
catch(IOException e)
           System.out.println(e.getMessage());
             e.printStackTrace();
             System.exit(1);
}where myServer is this:
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;
public class myServer implements Runnable {
private ServerSocket server = null;
public myServer(SSLServerSocket ss)
                     System.out.println("Created myServer instance with server socket");
     server = ss;
     newListener();
    private void newListener()
     System.out.println("Created new listener");
         (new Thread(this)).start();
    public void run()
     System.out.println("Listening for connections");
         Socket socket;
         try
          System.out.println("Trying to accept connection");
                                 socket = server.accept();
                              System.out.println("Accepted Connection, starting handshake");
                              ((SSLSocket)socket).addHandshakeCompletedListener(new HandshakeCompletedListener()
               public void     handshakeCompleted(HandshakeCompletedEvent event)
                    System.out.println("Handshake finished!");
                    System.out.println("\t CipherSuite:" +
                    event.getCipherSuite());
                    System.out.println("\t SessionId " +
                    event.getSession());
                    System.out.println("\t PeerHost " +
                    event.getSession().getPeerHost());
                              ((SSLSocket)socket).startHandshake();
         catch (IOException e)
             System.out.println("Class Server died: " + e.getMessage());
             e.printStackTrace();
             return;
         newListener();
}Most of this code came from the sun website, just a couple of tweaks for it to do what I wanted it to.

Similar Messages

  • I'm begging for help here.

    Today I made an awful mistake taking some very important photos and videos off of my iphone and placing them into a destop folder on my PC. The photos came off very easily by opening the the folder that was containing them and simply dragging and dropping them into a folder on my desktop. I decided to put some of the photos and videos that were taken with the phone back in the folder and it refuses to work. I want the photos back on my phone but it will not accept it. The photos and videos are not recognised by iTunes. Opening the folder, and minimizing iTunes to attempt to drag the files from the folder to my iPhone in iTunes will not work and I get an error saying "IMG_1191.MOV was not copied to the iPhone "Michael's iPhone 5" because it cannot be played on this phone."
    Please, I'm begging for help here. I just want my photos and videos back on my iPhone.
    My PC is running Windows7 and my iPhone is the latest software.

    You put photos onto your iPhone by syncing with iTunes.
    On your computer create a master folder for photos. Inside that folder create subfolders. Each subfolder will become a photo album on your iPhone after you sync. Do not create any additional layers of subfolders inside the first level of subfolder.
    Once you have the photo folders organized start iTunes on your computer and make sure you have iTunes 10.7 or later. iTunes 11.0.1 is the latest version. If you are running iTunes 11 start iTunes and use the View menu to View Sidebar.
    Then connect your iPhone to your computer. In iTunes on your computer select your iPhone in the left sidebar. Then select photos in the larger right window. Under Photos navigate to your photo folder. You can select to sync all photos or select just the photo albums you want on the iPhone. Then click on Apply or Sync.
    To remove these albums later do another sync but deselect the o longer wanted albums.

  • HELP - problem in running SSLSocket client/server application

    Hi,
    I want to create a SSLSocket based client/server application for this i have used EchoServer.Java and EchoClient.Java files. Both files are successfully compiled and when i ran EchoServer it throws an exception "Server certificate not found".
    I want to make a complete auto-controlled client/server application which will automatically gets certificate and all configuration itself from program because i will use both client and server application in as a servlet part.
    I did as per following instructions:
    -Create a keystore to hold the private and public keys for the server. e.g.
    keytool -genkey -keystore mykeystore -alias "myalias" -keypass "mysecret"
    -Export the X509 certificate from this store
    keytool -export -alias "myalias" -keystore mykeystore -file mycertfile.cer
    -Import this into a trustStore for the client
    keytool -import -alias "myalias" -keystore mytruststore -file mycertfile.cer
    -Run the server using the keystore
    java -Djavax.net.ssl.keyStore=mykeystore -Djavax.net.ssl.keyStorePassword="mysecret" EchoServer
    -Run the client using the truststore
    java -Djavax.net.ssl.trustStore=mytruststore -Djavax.net.ssl.trustStorePassword="mysecret" EchoClient localhost
    EchoServer.Java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.Socket;
    import javax.net.ssl.SSLServerSocket;
    import javax.net.ssl.SSLServerSocketFactory;
    public class EchoServer {
    public static int MYECHOPORT = 8189;
    public static void main(String argv[]) {
    try {
    SSLServerSocketFactory factory =
    (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslSocket =
    (SSLServerSocket) factory.createServerSocket(MYECHOPORT);
    while (true) {
    Socket incoming = sslSocket.accept();
    new SocketHandler(incoming).start();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(30);
    class SocketHandler extends Thread {
    Socket incoming;
    SocketHandler(Socket incoming) {
    this.incoming = incoming;
    public void run() {
    try {
    BufferedReader reader =
    new BufferedReader(new InputStreamReader(incoming.getInputStream()));
    PrintStream out =
    new PrintStream(incoming.getOutputStream());
    boolean done = false;
    while (!done) {
    String str = reader.readLine();
    if (str == null)
    done = true;
    else {
    System.out.println("Read from client: " + str);
    out.println("Echo: " + str);
    if (str.trim().equals("BYE"))
    done = true;
    incoming.close();
    } catch (IOException e) {
    e.printStackTrace();
    EchoClient.Java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import javax.net.ssl.SSLSocket;
    import javax.net.ssl.SSLSocketFactory;
    public class EchoClient {
    public EchoClient(){}
    public static final int MYECHOPORT = 8189;
    public static void main(String[] args) {
    /*if (args.length != 1) {
    System.err.println("Usage: Client address");
    System.exit(1);
    String sAddress="localhost";
    InetAddress address = null;
    try {
    //address = InetAddress.getByName(args[0]);
    address = InetAddress.getByName(sAddress);
    } catch (UnknownHostException e) {
    e.printStackTrace();
    System.exit(2);
    Socket sock = null;
    try {
    sock = new Socket(address, MYECHOPORT);
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(3);
    SSLSocketFactory factory =
    (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = null;
    try {
    sslSocket =
    (SSLSocket) factory.createSocket(sock, args[0], MYECHOPORT, true);
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(3);
    BufferedReader reader = null;
    PrintStream out = null;
    try {
    reader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    out = new PrintStream(sslSocket.getOutputStream());
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(6);
    String line = null;
    try {
    // Just send a goodbye message, for testing
    out.println("BYE");
    line = reader.readLine();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(6);
    System.out.println(line);
    System.exit(0);
    } // Client
    Can anybody will please help me to solve my problem i am using JDK1.4.2_07
    Thanks in advance.

    Hi,
    I want to create a SSLSocket based client/server application for this i have used EchoServer.Java and EchoClient.Java files. Both files are successfully compiled and when i ran EchoServer it throws an exception "Server certificate not found".
    I want to make a complete auto-controlled client/server application which will automatically gets certificate and all configuration itself from program because i will use both client and server application in as a servlet part.
    I did as per following instructions:
    -Create a keystore to hold the private and public keys for the server. e.g.
    keytool -genkey -keystore mykeystore -alias "myalias" -keypass "mysecret"
    -Export the X509 certificate from this store
    keytool -export -alias "myalias" -keystore mykeystore -file mycertfile.cer
    -Import this into a trustStore for the client
    keytool -import -alias "myalias" -keystore mytruststore -file mycertfile.cer
    -Run the server using the keystore
    java -Djavax.net.ssl.keyStore=mykeystore -Djavax.net.ssl.keyStorePassword="mysecret" EchoServer
    -Run the client using the truststore
    java -Djavax.net.ssl.trustStore=mytruststore -Djavax.net.ssl.trustStorePassword="mysecret" EchoClient localhost
    EchoServer.Java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.Socket;
    import javax.net.ssl.SSLServerSocket;
    import javax.net.ssl.SSLServerSocketFactory;
    public class EchoServer {
    public static int MYECHOPORT = 8189;
    public static void main(String argv[]) {
    try {
    SSLServerSocketFactory factory =
    (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslSocket =
    (SSLServerSocket) factory.createServerSocket(MYECHOPORT);
    while (true) {
    Socket incoming = sslSocket.accept();
    new SocketHandler(incoming).start();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(30);
    class SocketHandler extends Thread {
    Socket incoming;
    SocketHandler(Socket incoming) {
    this.incoming = incoming;
    public void run() {
    try {
    BufferedReader reader =
    new BufferedReader(new InputStreamReader(incoming.getInputStream()));
    PrintStream out =
    new PrintStream(incoming.getOutputStream());
    boolean done = false;
    while (!done) {
    String str = reader.readLine();
    if (str == null)
    done = true;
    else {
    System.out.println("Read from client: " + str);
    out.println("Echo: " + str);
    if (str.trim().equals("BYE"))
    done = true;
    incoming.close();
    } catch (IOException e) {
    e.printStackTrace();
    EchoClient.Java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import javax.net.ssl.SSLSocket;
    import javax.net.ssl.SSLSocketFactory;
    public class EchoClient {
    public EchoClient(){}
    public static final int MYECHOPORT = 8189;
    public static void main(String[] args) {
    /*if (args.length != 1) {
    System.err.println("Usage: Client address");
    System.exit(1);
    String sAddress="localhost";
    InetAddress address = null;
    try {
    //address = InetAddress.getByName(args[0]);
    address = InetAddress.getByName(sAddress);
    } catch (UnknownHostException e) {
    e.printStackTrace();
    System.exit(2);
    Socket sock = null;
    try {
    sock = new Socket(address, MYECHOPORT);
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(3);
    SSLSocketFactory factory =
    (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = null;
    try {
    sslSocket =
    (SSLSocket) factory.createSocket(sock, args[0], MYECHOPORT, true);
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(3);
    BufferedReader reader = null;
    PrintStream out = null;
    try {
    reader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    out = new PrintStream(sslSocket.getOutputStream());
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(6);
    String line = null;
    try {
    // Just send a goodbye message, for testing
    out.println("BYE");
    line = reader.readLine();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(6);
    System.out.println(line);
    System.exit(0);
    } // Client
    Can anybody will please help me to solve my problem i am using JDK1.4.2_07
    Thanks in advance.

  • Should i use secure sockets for my whole client/server application?

    Hi,
    I have a client server application, and I want to ensure that the login process is secure (i.e. use secure sockets). but I dont know how to switch back to a normal socket once that is done.
    So I am left thinking that i should just use SSL for my whole application, which can last pretty long. But I would rather not. Is there any other way of doing this?
    or should I just encrypt the login info using MD5 or something like that, then send it over an unsecure socket?
    thanks!

    Hey,
    Are you sure you haven't confused JGSS for JSSE?
    Imagine you have a client-server system and you sometimes want data sent over the wire to be encrypted... JGSS offers you this flexibility; if you a encrypted transmission, run ift through JGSS before transmitting it; if you don't want an encrypted transmission, bypass JGSS and just send the transmission.
    The benefit is the security (encryption) isn't hard-wired into you communications protocol i.e. TLS. JGSS has nothing to do with connections it is just protocol for securing messages, not sending them.
    You would need to establish the secure context but this could be done at startup and persist for the duration of you applicaiton invocation. You perhaps might need to implement a mechanism to identify encrypted messages on the receiving peer (so it knows to attempt decryption).
    Admittedly, kerberos seems like one of those 'inside-joke' things. I've come to realise if you don't have some sort of kerberos realm/server against which to authenticate - you need to swap it out as the underlying mechanism. How this is done I'm not sure yet, but I intend to find out today....further down the rabbit hole I go!
    If I discover anything helpful, I will let you know.
    Warm regards,
    D

  • Desperately need some help with client-server java programming

    Hi all,
    I'm new to client server java programming. I would like to work on servlets and apache tomcat. I installed the apache tomcat v 5.5 into my machine and i have sun java 6 also. I created a java applet class to be as a client and embed it into an html index file, like this:
    <applet code="EchoApplet.class" width="300" height="300"></applet>However, when I try to run the html file on the localhost, it print this error: classNotFoundException, couldn't load "EchoApplet.class" class. On the other hand, when I open the index file on applet viewer or by right clicking, open with firefox version 3, it works.
    I thought that the problem is with firefox, but after running the applet through the directory not the server, i found that the problem is not any more with firefox.
    Can anyone help me to solve this problem. I'm working on it for 5 days now and nothing on the net helped me. I tried a lot of solutions.
    Any help?

    arun,
    If the browser is going to execute $myApplet, first it must get the $myApplet.class from the server, right?
    So it follows that:
    1. $myApplet.class must be acessible to server, and
    2. the server must know exactly where to find $myApplet.class
    So, the simplest solution is to is put the $myApplet.class in the same directory as the HTML file which uses it... then your applet tag is simple:
      <applet height="200" width="400" code="$myApplet.class" ></applet>* The height & width attributes are required
    * Note the +.class+ is required in the code attribute (a common mistake).
    * This works uniformly (AFAIK) accross all java-enabled browsers.
    * There are incompatibilities with the codebase attribute. Poo!
    Cheers. Keith.

  • Help with client/server

    Hi guys, ive been developing a scrabble application lately, i have finished most parts of the game itself, so i decided to include the client/server (playing over LAN.)
    I have been able to make some features work like chat, update scores, switch turns.
    Now, i want to make a move so when a player plays, the tiles he drops on the board would update on the other player's game screen. I created a method and i have tried it in the normal game class(not client/server) and it works. But after coming up wiv a logic to send message to update the tiles, it doesnt work. I have attached pieces of the code pertaining to my problem.
    // Method to transfer the tiles (update the board with the tiles)
    //LetterBag class:
       public void transferTile(int tileindex, int cellindex, JPanel cell[]){
            for(int i=0;i<cell.length;i++){
                if(i==cellindex){
    // letterTile class contains all the tiles with each having its own index value (letterTile extends JLabel)
    //tiles is a Vector where i stored all the gameTiles.
                letterTile lt=(letterTile) tiles.elementAt(tileindex);
                    cell.add(lt);
    removeTile(tileindex);
    Multiplayerboard class:
    //Where i send the message to the server
    for(int i=0;i<ogaTile.size();i++){
    Vector v=(Vector)ogaTile.elementAt(i);
    int tindex=(Integer)v.elementAt(0);
    int cellindex=(Integer)v.elementAt(1);
    client.sendMessage("#-TRANSFERTILES-"+tindex+"-"+cellindex+"-*");
    //Tried printing out the above code and it prints out the right values
    Multiplayerclient class:
    lbag=new LetterBag();
    //multiplayer = new MultiplayerBoard(Player, this, chatter);
    //This is where the message is interpreted
    if (line.startsWith("#-TRANSFERTILES-")) {
    //anlyzer is the message string ( message line spits at"-")
    int x=Integer.parseInt(analyzer[0]);
    int y=Integer.parseInt(analyzer[1]);
    //multiplayer is instance of MultiplayerBoard class
    //cell is the gameboard panel in MultiplayerBoard class
    multiplayer.lbag.transferTile(x, y, multiplayer.cell);
    The problem is when i play, the game other client's application update the board with the tiles. I dont know where the problem is coming from maybe the logic or something else. Please any help/suggestion is really needed.

    dnt worry..
    jst solved it.. was an error on ma part

  • Help with client server chat2

    Hi aggain,
    And here is my Client part of program
    Server part is in topic "help with client server1
    CLIENT.JAVA
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    import javax.swing.*;
    public class Client {
    private static int SBAP_PORT = 5555;
    private static String server = "localhost";
    public static Socket socket = null;
    //main starts
    public static void main(String[] args) {
    try { //handle broken connection
    //set up connection to server, input, output streams
    try {
    socket = new Socket(server, SBAP_PORT);
    // handle wrong host/port errors
    catch (UnknownHostException e) {
    System.out.println("Unknown IP address for server.");
    System.exit(0);
    } //end catch UnknownHost
    catch (IOException ex) {
    System.out.println("No server found at specified port.");
    System.exit(0);
    } //end catch IOException
    catch (Exception exc) {
    System.out.println("Error :" + exc);
    System.exit(0);
    } //end cath Exception exc
    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    PrintWriter writer = new PrintWriter(output);
    while (true) {
    String client_in = JOptionPane.showInputDialog(null, "Client Request");
    System.out.println("Sending: " + client_in);
    writer.print(client_in);
    writer.flush();
    //read server entry and dispay
    String response = reader.readLine();
    if (response == null || response.equals("QUIT"))
    System.out.println("No data received");
    else
    System.out.println("Receiving: " + response);
    } //end try
    catch (IOException e) {
    System.out.println("Connection with server broken:" + e);
    System.exit(0);
    } //end catch IOException
    catch (Exception exp) {
    System.out.println("Error :" + exp);
    System.exit(0);
    } //end catch exp
    }//end main()
    }//end class Client

    http://forum.java.sun.com/thread.jspa?threadID=574466&messageID=2861516#2861516

  • Need help clarifying client/server TNS communication

    Im trying to get a clearer understanding of service/listener registration in the Oracle client/server architechure. Feel free to point out errors in my understanding.
    When an Oracle client connects to the server, it forms its connect descriptor based on the clients tnsnames.ora file. The client then checks the specified port on the host in the connect descriptor for a listener that is registered with the service defined in the
    (CONNECT_DATA =
    (SERVICE_NAME = TESTSERVICE)
    portion of the client's tnsnames file. Correct?
    Does the listener gets its list of SIDs its registered with from the SID_LIST section of the listener.ora file or the tnsnames file?
    If the listener gets its list of SIDs to register with from the tnsnames file, is that the tnsnames file on the server?
    If so, then what is the SID_LIST used for in the listener.ora file?
    Im trying to connect the dots and any help would be much appreciated.
    Thanks,

    Reading below documents would help you understand how client/server TNS communication works:-
    Listener Architecture
    http://download-east.oracle.com/docs/cd/B14117_01/network.101/b10775/architecture.htm#sthref445
    Configuring Naming Methods
    http://download-east.oracle.com/docs/cd/B14117_01/network.101/b10775/naming.htm
    Configuring and Administering the Listener
    http://download-east.oracle.com/docs/cd/B14117_01/network.101/b10775/listenercfg.htm

  • Help in client server project

    Asalam-o-Alikum!
    I m writing client server project. In that project there are many classes that are being used in both (client application and server application). Im using JCreator and also netbeans 5.5 IDE. Plz anyone can help that should i design 1 project for cilent and server. or 2 different projects 1 for client and 1 for server. If i have to use 2 different projects than how can I make available those classes to both projects (client and server) that are being shared by client and server. and i have to make 1 project than how can i run both client and server separately.
    thanks in advance.

    Aslam-o-Alikum!
    I am designing a new project that depends on another project. I want to use the classes made in previous project into my new project. Someone (as above) has told me to make the jar file of that class and set the class path to that jar file. Anyone can further tell me that how can set the class path of that project into my new project. And how to import the classes from that project that i have made previously???
    Example:
    I am designing project name "A" and i have to use a class "b" that not the part of project "A". But actually it is part of project "B". That i have made previously. Please tell how this can be achieved? making jar file of project "B" is right answere then how can i set the path of project "B" in project "A". and how to import class "b" into project "A". I am using JCreator pro 4.0
    This is the summary of obove posts. so plz dont read above posts just read this and plz help me if u could.
    Plz reply me with a simple example.
    Thanks in advance...!

  • Help with client server chat 1

    Hi,
    I have to create small multithreaded client/server. chat program. Server and client have to exchange messages using input boxes until user types QUIT. I did most of it(I think) but it seems that server does not receives client messages and input boxes are displayed only once. I can�t figure out what is the problem. Here is what I did .I know it�s not easy to understand somebody else�s code, but if anybody have some spare time?
    this is just a server part, client is in second posting
    SERVER.JAVA
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    import javax.swing.*;
    public class Server
    final int SBAP_PORT = 5555;
    //constructor
    public Server(){
    //set up server socket
    ServerSocket ss = null;
    try {
    ss = new ServerSocket(SBAP_PORT);
    } //end try
    catch (Exception e) {
    System.out.println("Could not create socket: Exception " + e);
    System.exit(0);
    } //end catch
    //chat with the client until user break the connection or enters QUIT
    try {
    while(true) {
    System.out.println("Server: Waiting for client to connect ...");
    Socket currentSocket = ss.accept();
    //create a new thread for each connection
    new ServerThread(currentSocket);
    } //end while
    } //end try
    catch (Exception e) {
    System.out.println("Fatal server error: " + e);
    }//end catch
    }//end constructor
    //inner class ServerThread to handle individual client connections
    private class ServerThread extends Thread {
    private Socket sock;
    private InputStream in=null;
    private OutputStream out=null;
    private BufferedReader reader = null;
    private PrintWriter writer = null;
    //constructor
    public ServerThread(Socket sock) {
    try{
    this.sock=sock;
    System.out.println("Server: Client connection established");
    start();
    }//end try
    catch (Exception e){}
    }//end constructor
    public void run() {
    try{
    in = this.sock.getInputStream();
    out =this.sock.getOutputStream();
    reader = new BufferedReader(new InputStreamReader(in));
    writer = new PrintWriter(out);
    while(true) {
    String server_response = JOptionPane.showInputDialog(null,"Server Response");
    System.out.println("Sending: " + server_response);
    writer.println(server_response);
    writer.flush();
    String line = reader.readLine(); //receives client request
    if (line == null || line.equals("QUIT"))
    System.out.println("No data received");
    else
    System.out.println("Received: " + line);
    }//end while
    }//end try
    catch (Exception e) {
    System.out.println("Connection to current client lost.");
    finally {
    try {
    sock.close();
    }//end try
    catch (Exception e) {}
    }//end finally
    }//end run
    }//end inner class ServerThread
    //main starts
    public static void main(String[] args) {
    new Server();
    }//end main()
    }//end class Server

    http://forum.java.sun.com/thread.jspa?threadID=574466&messageID=2861516#2861516

  • 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.

  • Begging for help!!!

    Hi, My bb recently crashed and I had reinstall all the software. After I reinstalled the new messenger I tried to restore my contacts and it keeps stating that I have to register my bb messenger with the bb messenger service. When I do that I keep getting this message "blackberry messenger failed to register with the blackberry messenger service. Registration is necessary to use the features of this application. Please ensure your device time is correctly set, open the my profile screen and check the blackberry messenger registration status". My operator, bb vendor, and local technical support have no idea how to solve this!!! Bb messenger works fine but I need to register to restore my contacts! Any help would be much appreciated... Thanks

    Hi there!
    I suggest the following steps:
    1) Register HRT
    Homescreen > Options > Advanced Options > Host Routing Table > (it does not matter which line is current) > Register Now
    2) Resend Service Books
    KB02830 Send the service books for the BlackBerry Internet Service
    3) Batt Pull Reboot
    Anytime random strange behavior or sluggishness creeps in, the first thing to do is a battery pop reboot. With power ON, remove the back cover and pull out the battery. Wait about a minute then replace the battery and cover. Power up and wait patiently through the long reboot -- ~5 minutes. See if things have returned to good operation. Like all computing devices, BB's suffer from memory leaks and such...with a hard reboot being the best cure.
    Hopefully that will get things going again for you! If not, then you should contact your formal support again -- your carrier. They have the ability to escalate into RIM if needed.
    Occam's Razor nearly always applies when troubleshooting technology issues!
    If anyone has been helpful to you, please show your appreciation by clicking the button inside of their post. Please click here and read, along with the threads to which it links, for helpful information to guide you as you proceed. I always recommend that you treat your BlackBerry like any other computing device, including using a regular backup schedule...click here for an article with instructions.
    Join our BBM Channels
    BSCF General Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • Begging for help : Swing: networking

    I am getting problems after problems....i did this Swing applet to "activate" the server so that it waits for a request. the first time i ran it i got the java.security.accessdenied....etc...
    I changed the java.security to grant all permissions....
    I ran the following code...
    it hangs..the button gets stuck....
    what s the problem..
    Do i also post the java.security file?
    PLEASE HELP.
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
         public class appSNServerFile extends JApplet implements ActionListener{
              JButton activate;
              JTextArea ta;
                   public void init(){
                        activate = new JButton("Activate the Server");
                        ta = new JTextArea(10,10);
                        Container con = getContentPane();
                        con.setLayout(new FlowLayout());
                        con.add(activate);
                        con.add(ta);
                        activate.addActionListener(this);
                        public void actionPerformed(ActionEvent e){
                             String temp="";
                             try{
                                  InetAddress ip = InetAddress.getLocalHost();
                                  ServerSocket s = new ServerSocket(2000);
                                  ta.setText("The Server's IP is "+String.valueOf(ip)+"\n");
                                  for(;;){
                                       Socket c = s.accept();
                                       ta.setText(String.valueOf("Request received from the client "+c+"\n"));
                                       DataInputStream din = new DataInputStream(c.getInputStream());
                                       DataOutputStream dout = new DataOutputStream(c.getOutputStream());
                                       String filename = din.readUTF();
                                       BufferedReader b = new BufferedReader(new FileReader(filename));
                                       String content = "";
                                       while(true){
                                            String t = b.readLine();
                                            if(t==null) break;
                                            content += t + "\n";
                                       ta.setText(String.valueOf(content));
                                       catch(Exception ioe){
                                            ta.setText(String.valueOf(ioe));
         //<applet code = appSNServerFile height = 300 width = 300></applet>

    Look up the Java API on ServerSocket.accept()
    It blocks until a client makes a connection with it.
    Ie. that call will hang there forever, until a client tries to connect.
    A better approach is to create a separate thread, which waits for a client connection. Something like........
    Note : Not compiled nor tested... but gives general approach.
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
         public class appSNServerFile extends JApplet implements ActionListener, Runnable {
              ServerBackgroundThread backThread = new ServerBackgroundThread();
              JButton activate;
              JTextArea ta;
                   public void init(){
                        activate = new JButton("Activate the Server");
                        ta = new JTextArea(10,10);
                        Container con = getContentPane();
                        con.setLayout(new FlowLayout());
                        con.add(activate);
                        con.add(ta);
                        activate.addActionListener(this);
                   public void actionPerformed(ActionEvent e)
                        if ( !backThread.isRunning() )
                             backThread.start();
         class ServerBackgroundThread extends Thread
              boolean isRunning = false;
              public ServerBackgroundThread ( )
                   super();
              public boolean isRunning ( )
                   return ( isRunning );
              public void run ( )
                   isRunning = true;
                        String temp="";
                        try
                             InetAddress ip = InetAddress.getLocalHost();
                             ServerSocket s = new ServerSocket(2000);
                             // ta.setText("The Server's IP is "+String.valueOf(ip)+"\n");
                             updateTextField ( "The Server's IP is "+String.valueOf(ip)+"\n" );
                             for(;;)
                                  Socket c = s.accept();
                                  // ta.setText(String.valueOf("Request received from the client "+c+"\n"));
                                  updateTextField (String.valueOf("Request received from the client "+c+"\n"));
                                  DataInputStream din = new DataInputStream(c.getInputStream());
                                  DataOutputStream dout = new DataOutputStream(c.getOutputStream());
                                  String filename = din.readUTF();
                                  BufferedReader b = new BufferedReader(new FileReader(filename));
                                  String content = "";
                                  while(true)
                                       String t = b.readLine();
                                       if(t==null) break;
                                       content += t + "\n";                                   
                                  // ta.setText(String.valueOf(content));
                                  updateTextField ( String.valueOf(content));
                        catch(Exception ioe)
                             // ta.setText(String.valueOf(ioe));
                             updateTextField ( String.valueOf(ioe));
                        finally
                             isRunning = false;
              public void updateTextField ( String message )
                          // IMPORTANT : You can't update a Swing component in another
                          // Thread.  You must update it in a "Swing friendly" manner.
                          // Hence this helper function.
                   final Runnable runnable = new Runnable()
                       public void run()
                            ta.setText ( message );
                       } // run
                   };    // runnable
                   SwingUtilities.invokeLater(runnable);
         //<applet code = appSNServerFile height = 300 width = 300></applet>

  • Help with client server program!

    OK, I've gotten this far on my own, but now I need a little help. My program is supposed to allow a client to type in a file name in a JTextField and have the server return the file contents. Someone please let me know where I have erred. Below is the code for server.java and client.java. Thanks for your help!
    import java.io.*;
    import java.net.*;
    public class Server
    private BufferedWriter output;
    private BufferedReader input;
    private Socket connection;
    String str;
    public void runServer ( )
    int counter = 0;
    try
    ServerSocket server = new ServerSocket ( 8189 );
    while ( counter < 2 )
    connection = server.accept ( );
    getStreams ( );
    processConnection ( );
    closeConnection ( );
    counter++;
    catch ( IOException ioException )
    ioException.printStackTrace ( );
    private void getStreams ( ) throws IOException
    output = new BufferedWriter ( new OutputStreamWriter ( connection.getOutputStream ( ) ) );
    output.flush ( );
    input = new BufferedReader ( new InputStreamReader ( connection.getInputStream ( ) ) );
    private void processConnection ( ) throws IOException
    String fileName = input.readLine ( );
    File file = new File ( fileName );
    BufferedReader fileInput = new BufferedReader ( new InputStreamReader
    ( new FileInputStream ( file ) ) );
    BufferedWriter writer = new BufferedWriter ( new FileWriter ( file ) );
    while ( ( str = fileInput.readLine ( ) ) != null )
    output.write ( str );
    output.newLine ( );
    output.flush ( );
    writer.close ( );
    private void closeConnection ( ) throws IOException
    output.close ( );
    input.close ( );
    connection.close ( );
    public static void main ( String [ ] args )
    Server application = new Server ( );
    application.runServer ( );
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame
    private JTextField enterField;
    private JButton saveButton;
    private JTextArea displayArea;
    private BufferedWriter output;
    private BufferedReader input;
    private String message = "";
    private Socket connection;
    public Client ( )
    super ( "Client" );
    Container container = getContentPane ( );
    JPanel panel = new JPanel ( );
    JLabel displayLabel = new JLabel ( "Enter file name to retrieve: " );
    panel.add ( displayLabel );
    enterField = new JTextField ( 10 );
    enterField.setEnabled ( false );
    enterField.addActionListener (
    new ActionListener ( )
    public void actionPerformed ( ActionEvent event )
    sendFile ( event.getActionCommand ( ) );
    panel.add ( enterField );
    saveButton = new JButton ( "Save Changes" );
    saveButton.addActionListener (
    new ActionListener ( )
    public void actionPerformed ( ActionEvent event )
    sendFile ( event.getActionCommand ( ) );
    panel.add ( saveButton );
    container.add ( panel, BorderLayout.NORTH );
    displayArea = new JTextArea ( );
    container.add ( new JScrollPane ( displayArea ), BorderLayout.CENTER );
    setSize ( 500, 400 );
    setVisible ( true );
    public void runClient ( )
    try
    connection = new Socket ( InetAddress.getLocalHost ( ), 8189 );
    getStreams ( );
    processConnection ( );
    closeConnection ( );
    catch ( EOFException eofException )
    System.out.println ( "Server terminated connection" );
    catch ( IOException ioException )
    ioException.printStackTrace ( );
    private void getStreams ( ) throws IOException
    output = new BufferedWriter ( new OutputStreamWriter ( connection.getOutputStream ( ) ) );
    output.flush ( );
    input = new BufferedReader ( new InputStreamReader ( connection.getInputStream ( ) ) );
    private void processConnection ( ) throws IOException
    enterField.setEnabled ( true );
    message = ( String ) input.readLine ( );
    while ( message != null )
    displayArea.append ( message + "\n" );
    private void closeConnection ( ) throws IOException
    output.close ( );
    input.close ( );
    connection.close ( );
    private void sendFile ( String message )
    try
    output.write ( message );
    output.flush ( );
    catch ( IOException ioException )
    displayArea.append ( "\nError writing" );
    public static void main ( String [ ] args )
    Client application = new Client ( );
    application.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    application.runClient ( );

    Well, where do YOU think you erred?
    Are you getting any error messages? If so, what are they?
    Are you getting any behavior other than what you expected? If so, what behavior did you expect, and what behavior are you getting instead?
    I can't speak for the others, but I'm much more inclined to help if you had at least said something like...
    "If I type in the name of a file that doesn't exist, a JPanel pops up with nothing written in it. This is behavior I want. If I type in the name of a file that does exist, a JPanel should pop up with the contents of that file, but unfortunately, it thinks there's nothing in the file. I know my program can at least find the file because I added a routine to write the name of the file within the JPanel if it can find the file."
    It is much easier for me to just write my own program to display the contents of a file, than it is for me to read your mind and discover what problems YOU are having with it.

  • Help with Client/Server communication

    Im working on a project for university, and one aspect of it is downloading files from a remote computer.
    The majority of my project so far has been using RMI only, for browsing the remote computer, deleting files, renaming files, creating new directories and searching for files. All of this is done via a GUI client, with a server running on the server machine.
    Ive now reached the part where I'll need to implement the downloading of files. I want the user to select a file from within the GUI and click download, and get it off the server.
    I dont need any help with event handlers or getting the contents of the remote computer or anything of that sort.
    Consider when I have the name of the file that I want to download from the client.
    Im having trouble understanding how exactly its going to work. Ive seen examples of file transfer programs where the user types in the name of the file in the command line which they want to download. But my implementation will differ.
    Every time the user clicks the button, I have to send to the server the name of a different file which will need to be downloaded.
    I imagine in the event handler for the Download button I'll be creating a new socket and Streams for the download of the file that the user wants. But how am I to send to the client a dynamic file name each time when the user tries to download a different file?
    I am a bit new at this, and Ive been searching on the forums for examples and Ive run through them, but I think my situation is a bit different.
    Also, will RMI play any part in this? Or will it purely be just Socket and Streams?
    I'll also develop an Upload button, but I imagine once I get the Download one going, the Upload one should be much harder.
    Any ideas and help would be appreciated.

    Hi
    I'm no RMI expert... and I did not understand your question very well....
    I think you should do this procedure:
    you should send a request for the file from the client to the server . then a new connection between the two machines should be made which will be used to send the file.
    by using UDP you will achive it quite nicely...
    //socket - is your TCP socket  you already use on the client...
    //out - socket's output stream
    byte [] b=new String("File HelloWorld.java").getBytes();
    // you should use a different way for using this rather than using strings...
    out.write(b);
    DatagramSocket DS=new DatagramSocket(port);
    DS.recieve(packet); //the data is written into the packet...on the server side you should...
    //socket - is your TCP socket  you already use on the server...
    //in - socket's input stream
    byte [] b=new byte[256];
    out.read(b);
    /*Here you check what file you need to send to the client*/
    DatagramSocket DS=new DatagramSocket(server_port);
    byte [] data=//you should read the file and translate it into bytes and build a packet with them
    DS.send(packet); //the data is in the packet...This way the server sends the required file to the client .....
    I hope it will help, otherwise try being clearier so I could help you...
    SIJP

Maybe you are looking for

  • Adobe reader XI not responding

    Like so many others, I have started to get a 'non responding' response when trying to use adobe reader. I have posted a new question as I have yet to find an answer on the myriad of forums that I have searched. I am using adobe reader XI.0.08 on Wind

  • Modification of message type 519 in transaction ORFA

    Message Number 519 says that there is an customizing inconsistency for Cost-of-Sales Accounting. Since cost-of-sales accounting is active but the functional areas is not set as an account assignment object. There is a need to keep cost-of-sales activ

  • Calling RFC funtions from VBA

    Hi all, I would like to call RFC funtions from VBA, could you please advise on what library should I set reference to? A piece of sample code would also be highly appreciated. Thanks in advance. Tomas

  • Mapping debbuging error:DBG1006: Error while initializing test data

    Hi, I have created a mapping in which I am trying to delete data from a table based on exisitence of rows in another table with a filter condtion in between them.When i try to run the debbugger, it throws following error: ============ Analyzing map f

  • Installing an iPhone application

    This question was posted in response to the following article: http://help.adobe.com/en_US/as3/iphone/WS144092a96ffef7cc-4ae52ec4126ab9d6ce6-8000.html