Help on Sockets

I would appreciate if someone could help on the following problem
Scenario:
1, Socket client is running on AS400 written using Java.
2, I am trying to connect to a Unix box from AS400 using the above java socket client I am getting the following error.
Couldn't get I/O for the connection to: venus.
Exception :A remote host refused an attempted connect operation.
java.net.ConnectException: A remote host refused an attempted connect operati
on.
java/lang/Throwable.<init>(Ljava/lang/String;)V+4 (Throwable.java:81)
java/net/PlainSocketImpl.connectToAddress(Ljava/net/InetAddress;I)V+14
(PlainSocketImpl.java:124)
java/net/PlainSocketImpl.connect(Ljava/net/InetAddress;I)V+10 (PlainSoc
ketImpl.java:111)
java/net/Socket.<init>(Ljava/lang/String;I)V+5 (Socket.java:89)
testAS400e.main([Ljava/lang/String;)V+0 (testAS400e.java:21)          
Can someone throw some light on this?
Your help would greatly appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

This is the error you will get if you cannot connect to a host. This is a normal error that your program should be able to handle. Probably you are trying to connect to the host at a port that no program is listening on. If you can telnet to that port, from the same machine then your jvm is messed up, otherwise it's a network problem.
In java, all connection problems, DNS lookup problem, connection errors, routing errors ,etc... show up as exceptions thrown whenever the problem is encountered. During connection , during read/write to the socket, whatever. So whenever you do anything with the socket, be prepared to encounter an error. Most of the time you can only try to reconnect and restablish the state you were in last, but that is not always possiable.
If you are trying to do a simple HTTP transaction, I would suggest using the java.net.URL class as it will do most of the work you want for you. If you are using the newest 1.4 jdk, then it will even handle ssl tranasctions.

Similar Messages

  • Need help on Socket and HTTP

    Hi,
    I need help ... please ... I have to use socket and not HTTPURLConnection
    I try to connect with a socket to a web server (apache2) and request one page but two times.
    The first time it works well but the second one it doesn't ... I get a null message.
    Why ?
    Does the server close the socket as soon as the page is sent ?
    If it doesn't how I can continue sending and receiving data on the same socket ?
    Here is my code:
    package test;
    import java.net.*;
    import java.io.*;
    public class Test
    private String laRequete = new String(
    "POST http://localhost:5577/Test/ HTTP/1.0\r\n"+
    "Host:localhost:5577\r\n"+
    "\r\n");
    PrintWriter laSortie;
    BufferedReader lEntree;
    Socket laSocketTCP;
    public Test()
    String tmp;
    try
    laSocketTCP = new Socket("localhost", 5577);
    laSortie = new PrintWriter(laSocketTCP.getOutputStream());
    lEntree = new BufferedReader(new InputStreamReader(laSocketTCP.getInputStream()));
    laSortie.println(laRequete);
    laSortie.flush();
    // Premier essai OK
    System.out.println(lEntree.readLine());
    while((tmp = lEntree.readLine()) != null)
    System.out.println(tmp);
    // Second essai => Not OK
    laSortie.println(laRequete);
    laSortie.flush();
    System.out.println(lEntree.readLine());
    while((tmp = lEntree.readLine()) != null)
    System.out.println(tmp);
    catch (Exception e)
    e.printStackTrace();
    public static void main(String args[])
    Test tp = new Test();
    Here is the result of the execution
    HTTP/1.1 200 OK
    Date: Wed, 29 Sep 2004 08:35:35 GMT
    Server: Apache/2.0.51 (Win32)
    Last-Modified: Wed, 29 Sep 2004 08:27:57 GMT
    ETag: "23a46-9a-56c93f9a"
    Accept-Ranges: bytes
    Content-Length: 154
    Connection: close
    Content-Type: text/html; charset=ISO-8859-1
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE> Index Test 1 </TITLE>
    </HEAD>
    <BODY>
    Test 1
    </BODY>
    </HTML>
    null
    Thanks, bye.

    Send an HTTP 1.1 request instead of a 1.0 request.
    HTTP 1.0 does not support keeping the connection open, so yes, the server closes the connection.
    Dave.

  • Need help identifying socket part

    i recently tried to repair my ibook g4 14" and i the process of pulling the power adapter microphone cable connector, (the blue and white cable that plugs into the logic board in the upper left hand side right next to the phone cable) i pulled the socket out of the logic board, does anyone here know what that piece is or where i can find it and is it even possible to repair this on my own, any help would be greatly appreciated, on the side of piece it says "aces 02" if that helps
    -ryan

    Hey Ryan,
    .. i pulled the socket out of the logic board, does anyone here know what that piece is or where i can find it and is it even possible to repair this on my own,
    That's the power socket and I have done that as well. I made a special tool to do that now so I don't do that anymore.
    I have repaired two of these but you need some experience soldering SMT circuits.
    In both cases the trace under the socket is tiny tiny so I had to trace continuity to the opposite side of the circuit board. These were discrete SMT devices and were gigantic compared to the traces. I led the wires back through the board and soldered them to the bottom of the socket where the traces had pulled out.
    Since this happens so often I recommend that you don't disconnect this plug if at all possible. Rather swing the top case out of the way and tape it to the display along with the top shield.
    Richard

  • Help in socket programming

    Actually my client and server ,both are running on same m/c.
    client code is
    Socket s1;
    try{
    s1 = new Socket("localhost",5678);
    catch(Exception e){}
    Server Code is
    ServerSocket serverSocket = new ServerSocket(port);
    while(true) {
         Socket socket = serverSocket.accept();
         InetAddress inetAddress = socket.getInetAddress();
         new Thread(new SocketNode(socket)).start();
    where constructor for SocketNode is like this :-
    public
    SocketNode(Socket socket) {
    this.socket = socket;
    try {
    ois = new ObjectInputStream(socket.getInputStream());
    catch(Exception e) {
    cat.error("Could not open ObjectInputStream to "+socket, e);
    It throws exception in opening object input stream.
    Could anybody suggest the possible reasons for it.
    error is something like this :-
    ERROR [main] Logger.SocketNode (<init>:35) - Could not open ObjectInputStream to Socket[addr=/127.0.0.1,port=1800,localport=5678]
    java.net.SocketException: Connection reset by peer: JVM_recv in socket input stream read
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at Logger.SocketNode.<init>(SocketNode.java:32)
    at Logger.SocketServer.main(SocketServer.java:40)
    I will be really thankful, if anybody can help in this regards

    Hi Neetika,
    Your error is telling that
    your client program has
    teminated before server
    could create an ObjectInput
    Stream. So, for this you KEEP
    your client program
    alive for some time( So that
    socket object in client side
    is not swapped out by Garbage
    collector ).
    and then you will not get above error.
    cheers!

  • Need help with sockets!

    I am fairly new to network programming. All help is very appreciated!
    I know how to work with sockets and serversockets, and how to transmit data between the host and the clients. My problem is that I have no idea how to get my working program to work online.
    -It works fine when I have both the client and host programs running on my computer.
    -It works fine when I have the host on one computer (192.168.1.103), and the client running on another one (192.168.1.102 I think). I guess in this case I'm just using the linksys network, not the internet.
    -IT DOES NOT WORK WHEN I upload the files to my website, and run them from there. I am not sure what the cause is; the host correctly creates the serversocket and waits, but never receives a connection to the client. The client seems to connect; it does not throw any exceptions, and creates a socket, but never actually communicates with the host.
    Could the problem be with my applets' permissions?
    What hostname/IP should I have the client connect to? It is on the same server, so would localhost work, or do I need to connect to my websites ip, or to the hostname?
    What other problems could there be?!?!?!?!
    Thank you so much for your help!!!!!!!!!!

    Donv7 wrote:
    1) Is the server program running on the same machine as the webserver?
    2) How are you opening this Socket in the applet? You mentioned something about localhost, that would be wrong. You should use the www hostname. Same as the host that served the HTML that the applet lives in.1- My server program and client program are actually the same thing. This doesn't sound too good.
    And applet is not a suitable endpoint for a P2P application. An applet is going to be a client. Not a server.
    Are you actually running a server (of your program) on the webserver? Or are you hoping that two applets will talk to each other with one acting as a server? Because that's not going to work.

  • HELP : Convert socket programming from Ipv4 to IPv6

    Hi all,
    I need help in converting my Ipv4 socket programing to Ipv6. How can I do this? I already have an Ipv4 socket programming that is working but when I tried to convert it to Ipv6 it doesn't work .
    this is my Ipv4 socket programming :
    DatagramPacket sendPacket;
    DatagramSocket sock;
    ip = jtfDIP.getText().trim();
    try{
    sock = new DatagramSocket();
    add = InetAddress.getByName(ip);
    sendPacket = new DatagramPacket(buf,buf.length,add,port);
    Please help me. How can I convert this to Ipv6. Thank you.

    Socket sock = new Socket("host");
    or
    Socket sock = new Socket("192.168.1.1");
    or
    Socket sock = new Socket("www.host.com");
    or
    Socket sock = new Socket("hhhh.hhhh.hhhh.hhhh");
    Get it? Just use whatever host, domain name, or IP you need, the underlying native code does the work - you'll never need to do anything, for the most part.

  • Help regarding socket and postgresql

    hi, i found this error while im generating a report
    for my system, "Aging of Accounts Receivables"
    hope someone might give me a hint to what should i do.
    here's my StackTrace:
    ***Exception:
    org.postgresql.util.PSQLException: The connection attempt failed because Exception: java.net.BindException: Address already in use: connect
    Stack Trace:
    java.net.BindException: Address already in use: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at java.net.Socket.connect(Socket.java:469)
    at java.net.Socket.<init>(Socket.java:366)
    at java.net.Socket.<init>(Socket.java:179)
    at org.postgresql.core.PGStream.<init>(PGStream.java:47)
    at org.postgresql.jdbc1.AbstractJdbc1Connection.openConnection(AbstractJdbc1Connection.java:197)
    at org.postgresql.Driver.connect(Driver.java:139)
    org.postgresql.util.PSQLException: The connection attempt failed because Exception: java.net.BindException: Address already in use: connect
    Stack Trace:
    java.net.BindException: Address already in use: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at java.net.Socket.connect(Socket.java:469)
    at java.net.Socket.<init>(Socket.java:366)
    at java.net.Socket.<init>(Socket.java:179)
    at org.postgresql.core.PGStream.<init>(PGStream.java:47)
    at org.postgresql.jdbc1.AbstractJdbc1Connection.openConnection(AbstractJdbc1Connection.java:197)
    at org.postgresql.Driver.connect(Driver.java:139)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
    at org.postgresql.jdbc2.optional.BaseDataSource.getConnection(BaseDataSource.java:72)
    at org.postgresql.jdbc2.optional.BaseDataSource.getConnection(BaseDataSource.java:55)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
    at org.postgresql.jdbc2.optional.BaseDataSource.getConnection(BaseDataSource.java:72)
    at org.postgresql.jdbc2.optional.BaseDataSource.getConnection(BaseDataSource.java:55)
    at org.postgresql.jdbc3.Jdbc3ConnectionPool.getPooledConnection(Jdbc3ConnectionPool.java:39)
    at org.postgresql.jdbc3.Jdbc3ConnectionPool.getPooledConnection(Jdbc3ConnectionPool.java:39)
    at org.postgresql.jdbc2.optional.PoolingDataSource.getPooledConnection(PoolingDataSource.java:406)
    at org.postgresql.jdbc2.optional.PoolingDataSource.getConnection(PoolingDataSource.java:338)
    at csfwdbillingmodules.dbConnect.<init>(dbConnect.java:73)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.processAccountAR(frmAgingOfAccounts.java:794)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.genDetailedReport(frmAgingOfAccounts.java:1102)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.doInBackground(frmAgingOfAccounts.java:406)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.doInBackground(frmAgingOfAccounts.java:400)
    at javax.swing.SwingWorker$1.call(SwingWorker.java:279)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at javax.swing.SwingWorker.run(SwingWorker.java:319)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    End of Stack Trace
    at org.postgresql.jdbc2.optional.PoolingDataSource.getPooledConnection(PoolingDataSource.java:406)
    at org.postgresql.jdbc2.optional.PoolingDataSource.getConnection(PoolingDataSource.java:338)
    at csfwdbillingmodules.dbConnect.<init>(dbConnect.java:73)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.processAccountAR(frmAgingOfAccounts.java:794)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.genDetailedReport(frmAgingOfAccounts.java:1102)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.doInBackground(frmAgingOfAccounts.java:406)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.doInBackground(frmAgingOfAccounts.java:400)
    at javax.swing.SwingWorker$1.call(SwingWorker.java:279)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at org.postgresql.jdbc1.AbstractJdbc1Connection.openConnection(AbstractJdbc1Connection.java:208)
    at org.postgresql.Driver.connect(Driver.java:139)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
    at org.postgresql.jdbc2.optional.BaseDataSource.getConnection(BaseDataSource.java:72)
    at org.postgresql.jdbc2.optional.BaseDataSource.getConnection(BaseDataSource.java:55)
    at org.postgresql.jdbc3.Jdbc3ConnectionPool.getPooledConnection(Jdbc3ConnectionPool.java:39)
    at org.postgresql.jdbc2.optional.PoolingDataSource.getPooledConnection(PoolingDataSource.java:406)
    at org.postgresql.jdbc2.optional.PoolingDataSource.getConnection(PoolingDataSource.java:338)
    at csfwdbillingmodules.dbConnect.<init>(dbConnect.java:73)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.processAccountAR(frmAgingOfAccounts.java:794)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.genDetailedReport(frmAgingOfAccounts.java:1102)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.doInBackground(frmAgingOfAccounts.java:406)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.doInBackground(frmAgingOfAccounts.java:400)
    at javax.swing.SwingWorker$1.call(SwingWorker.java:279)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at javax.swing.SwingWorker.run(SwingWorker.java:319)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    java.lang.NullPointerException
    at csfwdbillingmodules.dbConnect.query(dbConnect.java:96)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.processAccountAR(frmAgingOfAccounts.java:798)
    at csfwdbillingmodules.frmAgingOfAccounts$genAgingOfAccounts.genDetailedReport(frmAgingOfAccounts.java:1102)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at javax.swing.SwingWorker.run(SwingWorker.java:319)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
    at java.lang.Thread.run(Thread.java:619)
    End of Stack Trace
    here's my dbConnect.class:
    * dbConnect.java
    * Created on November 14, 2006, 5:06 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author darkoasis
    package csfwdbillingmodules;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketAddress;
    import java.net.SocketException;
    import java.net.SocketImpl;
    import java.sql.*; // All we need for JDBC
    import javax.naming.NamingException;
    import org.postgresql.jdbc3.Jdbc3PoolingDataSource;
    public class dbConnect
    extends java.lang.Object
    private Socket socket;
    private SocketImpl socketImpl;
    private int refPosition = 0;
    private Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource();
    private DriverManager drvMgr;
    private Connection db = null; // A connection to the database
    private Statement sql; // Our statement to run queries with
    private ResultSet results; // A result container
    private DatabaseMetaData dbmd; // This is basically info the driver delivers
    // about the DB it just connected to. I use
    // it to get the DB version to confirm the
    // connection in this example.
    /** Creates a new instance of dbConnect */
    public dbConnect()
    try
    this.source.setServerName("10.10.10.10");
    this.source.setDatabaseName("myDB");
    this.source.setUser("xxxx");
    this.source.setPassword("xxxx");
    this.db = this.source.getConnection();
    this.socket = new Socket();
    dbmd = this.db.getMetaData(); //get MetaData to confirm connection
    sql = this.db.createStatement(); //create a statement that we can use later
    catch (Exception ex)
    System.out.println("***Exception:\n"+ex);
    ex.printStackTrace();
    public ResultSet query(String strSQL)
    throws SQLException
    this.results = this.sql.executeQuery(strSQL);
    return this.results;
    public void update(String strSQL)
    throws SQLException
    this.sql.executeUpdate(strSQL);
    public void close()
    throws Exception
    this.db.close();
    this.socket.close();
    this.source.close();
    public boolean isClosed()
    throws SQLException
    return this.db.isClosed();
    i ran into some forums and found this:
    Hi Graham
    I'm making a bit of progress. I found a website that suggested the following
    This is a problem of the used sockets with Windows NT. You can request the active sockets with the command netstat. The problem is a function of:
    MaxUserPort (default 5000)
    KeepAliveTime (default 120)
    it suggested the workaround was connection pooling
    I have run netstat to look at the number of connections when the problem occurs and waited for the timeout to reset the os back to the minimum and on each occasion my report has run
    Does this sound logical?
    If so
    do you have any examples on connection pooling
    it seems that even if i have closed my database connection it still doesn't free my port that was used, that's why i get this error
    i am looking for a way to close my db connection and free its socket or port used at the same time, hope you can help,
    thanks in advance

    Duplicate of this thread, reply there:
    http://forum.java.sun.com/thread.jspa?threadID=5121873&messageID=9426716#9426716

  • Urgent Help in Socket Programming

    Hello Friends
    I have created a ChatServerApp.java and ChatClient.java as applet files. If i try to execute the chat using appletviewer, the chat module works fine. But when i embed in IE, the chat module shows me error. the error i have given below:
    java.security.AccessControlException: access denied (java.net.SocketPermission 203.101.33.160 resolve)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at ChatServer.CreateServer(ChatServerApp.java:123)
         at ChatServerApp$1.mouseReleased(ChatServerApp.java:36)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Button.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)java.lang.NullPointerException
         at ChatServer.listenServer(ChatServerApp.java:138)
         at ChatServer.run(ChatServerApp.java:106)
         at java.lang.Thread.run(Unknown Source)
    Can any one please help me to sort out this problem
    Thanks
    S.Srivignesh ([email protected])

    The browser limits the operations you can perform based on the security settings. You need to sign the jar and allow socket connections.

  • Need help! Socket connection

    Hi, I need some help to solve my problem that has taken me too much time. My client class sends a small message in bytes (37 bytes) to the server class , the server receives the message, processes and returns the result to the client. Everything is OK. Then the client sends a big message (777 bytes) also in bytes, the server just stops. I check the server side and see that it receives around 198913 bytes after a number of times of 0 byte.
    If I switch the order of the messages, sending the big message (777 bytes) first then the small (37 bytes), the server processes the big message successfully then stops. And it receives around 9473 bytes ( for the small message). Any help or suggestions would be very appricaited. This is my code:
    //client class
    public class Client{
    protected void startAgent(String hostName, int portNum, String clientName, String username, String password){
    outStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    inStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    // small message
    reply = login(username, password);
    System.out.println(reply);
    //big message:
    reply = deposit(accountNumStr, amount , username, X509cert);
    System.out.println(reply);
    //login method
    public String login(String username, String password){
    String result = null;
    byte[] message;
    try{
    msgBuffer msgBuff = new msgBuffer();
    msgBuff.formatBuffer(protocolConst.OPERATION);
    msgBuff.addText("offerServices");
    msgBuff.addUserName(username);
    byte[] encPswd = encrypt(password, sessionKey, "DES");
    msgBuff.addPassword(encPswd);
    msgBuff.finishBuffer();
    sendMessage(msgBuff.buffer, msgBuff.len);
    result = inStream.readUTF();
    }catch(Exception e){
    System.out.println("[login]exception caught");
    e.printStackTrace();
    return result;
    //[deposit method:
    public String deposit(String accNum, double amount, String username, X509Certificate cert){
    String result = null;
    try{
    msgBuffer msgBuff = new msgBuffer();
    msgBuff.formatBuffer(protocolConst.OPERATION);
    msgBuff.addText("deposit");
    msgBuff.addUserName(username);
    byte[] encAccNum = encrypt(accNum, sessionKey, "DES");
    msgBuff.addAccount(encAccNum, "from");
    msgBuff.addDouble(amount);
    byte[] cbytes = cert.getEncoded();
    System.out.println("LEN OF CERT: " + cbytes.length);
    msgBuff.addCertificate(cbytes);
    msgBuff.finishBuffer();
    sendMessage(msgBuff.buffer, msgBuff.len);
    result = inStream.readUTF();
    }catch(Exception e){
    System.out.println("[deposit]exception caught");
    e.printStackTrace();
    return result;
    protected void sendMessage(byte[] message, int len)throws Exception{
    try{
    outStream.writeInt(len);
    outStream.flush();
    outStream.write(message);
    outStream.flush();
    }catch(Exception e){
    System.out.println("[cAgent]sendMessage: exception caught");
    throw e;
    //Server class
    public class connectionHandler extends Thread{
    public void run(){
    try{
    in = new DataInputStream(new BufferedInputStream(cSocket.getInputStream()) );
    out = new DataOutputStream(new BufferedOutputStream(cSocket.getOutputStream()) );
    //Server now is waiting for messages from the client
    String reply = null;
    while(true){
         size = in.readInt();
         if(size > 0){
         System.out.println("READ INT FROM CLIENT : " + size);
         buff = new byte[size];
         in.readFully(buff);
         reply = processMessage(buff);
         if(reply != null){
         out.writeUTF(reply);
         out.flush();

    Not knowing how your "msgBuffer" works, I'll take a guess: where you have outStream.write(message); you really mean outStream.write(message, 0, len);.

  • Need help with Socket prog using Java wireless toolkit

    Hi, I am not able to communicate between client (Palm emulator) and server (Java on computer) using Java Wireless toolkit.
    Can anyone please tell me a site that shows an example. I have seen a bunch of examples but they all run by importing com.sun.kjava which seems to have vanished into thin air. So I cannot run them. Someone please show me some lines of code that will send just one character from client Palm emulator to server. thanks.
    Syed

    hi,
    I hope that you already have the J2ME Toolkit and that your emulator works okay. In the toolkit you get several examples to show you how to program a MIDlet. One has to do with a HTTP client server connection. Also in the API documentation for the J2ME there is a Connector class that you used to set up this communication and in the description of this class it pretty thoroughly explains how to set up an HTTP protocol client.
    However, if you want to do some other kind of networking then you are pretty much out of luck, as the TCPIP socket protocol has not been fully implemented and is optional to the J2ME specifications, only the HTTP protocol is certain to be available. This means that mobile phone companies can add other networking functionality to their phone's java virtual machine if they feel like it. This is a bummer I know.
    I hope this helps.
    Cheers,
    Mark

  • Urgent! please help: why socket.setSoTimeout(ms) doesn't work precisely

    I wanted to set timeout for the sockets accepted by server as:
    Socket socket = server.accept();
    socket.setSoTimeout(5);
    Since I want the server to process next request (another thread) as soon as read block happened on the current one, I set the timeout to be extremely short. But it doesn't work. I intentionly blocked my testing client and timed my first .read() method from server. 200 ms actually escaped, no timeout happened. What could be the problem?

    You can't really expect processors to be that fine-grained. There are multiple factors:
    1) other apps are running (such as the OS), consuming processor time as well
    2) processor speed
    3) etc.

  • Want help in sockets

    welll my problem is very simple one ....
    i want to send request to server from my client side gui .....
    .... its like that
    i have one class server which uses socket server.......to connect by port........
    server.class .....
    i have one class client which uses socket to connect to serversocket.........
    client is running a gui..... which is like a chat window.......whenever u press a button it will get text from textfield and then its will add to list ..............
    my problem is that i want to send same string to server which is adding in list................
    here is the codess of 3 classes.........
    first server.class
    public class Server
    ServerSocket ss;
    Socket s;
    InputStream in;
    OutputStream out;
    String temp;
    Server() throws Exception
    new InputStreamReader(System.in);
    ss = new ServerSocket(1357);
    System.out.println("Waiting on port 1357");
    s = ss.accept(); // waiting here
    System.out.println("Client connectionestablished");
    in = s.getInputStream();
    out = s.getOutputStream();
    DataInputStream read = new DataInputStream(in);
    PrintStream write = new PrintStream( out );
    while (true){
    temp = read.readLine(); // reading request
    write.println("i get u ");
    System.out.println(" msg from client"+temp);
    // s.close();
    /////////////////////// now client side code ///////
    public class Client
    Socket s;
    Client() throws Exception
    s = new Socket("localhost", 1357);
    System.out.println("Connected to on port 1357");
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    PrintStream write = new PrintStream( out );
    DataInputStream read = new DataInputStream(in);
    //////////////////////////calling gui//////////////////////
    Framee ff=new Framee();
    ff.Do();//////////prints gui
    String abc=" ";
    while(true){
    abc=ff.GetSend();
    write.println(abc); //REQUEST
    String temp = read.readLine(); //READING RESPONSE
    System.out.println("Response server " + temp);
    /////////////////////////////now Gui classs/////////////////////////////////////
    .....GUi(){
    public void Do(){
    f = new Frame();
    b1 = new Button("Ok");
    tf1 = new TextField(10);
    b1.addActionListener(new Alist());
    b2 =new Button("close");
    b2.addActionListener(new Alist());
    l = new List();
    BorderLayout bl= new BorderLayout();
    f.setLayout(bl);
    l.add(" ");
    f.add(l, BorderLayout.CENTER);
    f.add(b2, BorderLayout.NORTH);
    f.add(b1, BorderLayout.WEST);
    f.add(tf1, BorderLayout.SOUTH);
    f.setSize(300,300);
    f.setTitle("This is the title");
    f.show();
    public String GetSend(){
    String get=" ";
    get = l.getSelectedItem();
    // get=tf1.getText();
    return get;
    public class Alist implements ActionListener
    public void actionPerformed(ActionEvent e){
    if(b2== e.getSource())
    System.out.println(" na ");
    System.exit(0);
    if(b1==e.getSource()){
    String get=" ";
    get=tf1.getText();
    l.add(get);
    tf1.setBackground(Color.CYAN);
    // System.out.println(" yaap >>> "+get);
    tf1.setText(" ");
    ..................................... now i want that wtever is in List l of Gui ....it should be going to server......and aslo server and client should nt keep the cpu busy ....as they r doing in that code....... thanks in advance

    first you will have to digitize the stream, then cut it up into packets of handlable size, then you just sent them out over a valid socket connection.
    Yes, I know this is very simple, what part are you having toubles with?

  • Help in Socket Programing Plz

    Hi everyBody!!!
    I m writing a client/server program in which client requests to the server to get the contents of the directory of the server computer (path of the directory is specified by client).
    Server gets the contents fo the director by using the listFile() method and writes that contents onto the socket.
    but the problem is:
    how i can the read that contents from client side? server writes an array of type File onto the socket by using writeObject() method. And client definately will use readObject() method. but how i can read an array of type File from the client side???

    You gave the answer yourself: The Server may write the ARRAY of Files using write Objects and the Client will use readObject. Arrays are Objects too, so do not loop but just write:
    On server Side
    File [] allFiles = getThemFromSomewhere();
    ObjectOutputStream oout = ...;
    oout.writeObject(allFiles); // no loop here!
    ...On client side:
    ObjectInputStream oin = ...;
    File [] allFiles = (File[])oin.readObject()
    ...Well I don't really understand the way you want to do this, because the Files descriptions will be System dependent (and for FileTransfer FTP was created), so this will only make sense when you do interprocess communication on the same system. What do you want to achieve?

  • I need help with socket connection pooling please

    I need a basic connection pooling system for the code below users sets number connections 5 etc.
    <main class>
    s = new ListService(ssock.accept(),serverDir); //give list to client
    Thread t = new Thread(s);
    t.start();
    <main class>
    class ListService implements Runnable
    Socket client;
    String serverDir;
    public ListService(Socket client,String serverDir)
    this.client = client;
    this.serverDir = serverDir;
    public void run()
    try
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
    // send something to client
    catch(Exception e)
    System.out.println(e);
    System.out.println("client disconnected\n");
    catch(Exception e){}
    Thank you so much

    My code already accepts multi clients I need pooling only 5 clients can be using the server at a time when one client disconnects that means another incoming client can enter the pool to use the server.
    I tried to do a counter so when a connection is made it increments and then if counter>=numOfClients
    set a variable to true or false and this is sent with the server setup so it determines if the server code is run or it just closes the connection but there is no way I can access the counter variable from within a runnable class thread when a client closes connection it should -1 from the variable
    thanks

  • Help on socket ! very urgent !!!

    Hi all,
    i am developing a client app that connects to a server...
    for example i have the constuctor of a socket that connects to a server..the server requires the ipaddress and local port of the client for security reasons...so my socket constructor looks like this client = new Socket (remote ipaddress, remote port, local ipaddress, local port) ..this works fine...but the problem is that the server sends messages to the local port.....how do i make sure that java does not bind..the local port..i mean for it to be freed..cos it seems java is binding it.
    Thanks.

    Two options come to mind:
    1) Use UDP instead of TCP (although this should not be used for critical data because delivery is not guaranteed).
    2) If you still want to use TCP then have the client connect to the server on a known port. When it does, the server tells the client of a new, unique, port. Then the client disconnects and reconnects on the new port. his leaves the original "public" port free for other clients to connect to.

Maybe you are looking for

  • My app store is not working on my ipad

    I cannot seem to download anything from the app store on my iPad

  • Error Message while trying to open media manager

    When I try to open the media manager on the Blackberry Desktop Manager for my Storm, a window opens with the following: Microsoft Visual C++ Runtime Library Runtime Error c:\programfiles\roxio\mediamanager9\mediamanager.e​xe This application has requ

  • ADOBE DIGITAL EDITION 2

    Adobe Digital Edition Reader wont open up and accept files from kobo in smashword zip format says not supported

  • Set password on WRT54G router

    Please tell me where to go to set a password that will securethe network on my Linksys router. 

  • Can't get Firefox to import bookmarks

    Installed a new drive, have tried/followed all the tutorials (correctly I'd like to think), using the export function I have copied both .json and .html files to other drives, but when importing I don't get my bookmarks, just the stock/basic/pre-set