Sockets and Ports and DataInputStreams

I think this is just a basic TCP/IP networking question: When I open a socket connection to a remote ip address/port, what port am i receiving data on via my DataInputStream? Is it the same port I opened the remote connection on, 80, or what?
thanks,
Abraham

int answer = yourSocket.getLocalPort();

Similar Messages

  • Whats socket and port ??

    Hi,
    iam new to sockets...
    i dont know whats the difference between sockets and ports

    http://java.sun.com/docs/books/tutorial/networking/sockets/definition.html

  • Implementing sockets and threads in a jframe gui program

    Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
    I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
    I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
    listening socket:
         private void listeningSocket()
                ServerSocket serverSocket = null;
                boolean listening = true;
                try
                    //listen in port 4444;
                    serverSocket = new ServerSocket(4444);
                catch(IOException x)
                    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
                while(listening)
                    client_thread w;
                    try
                       w = new client_thread(serverSocket.accept(), jTextArea1);
                       Thread t = new Thread(w);
                       t.start();
                    catch(IOException x)
                         JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
            }thread class:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    * @author jonathan
    public class client_thread extends Thread
         //define new socket object
        private Socket client_user = null;
        private JTextArea textArea;
        public client_thread(Socket client_user, JTextArea textArea)
            this.client_user = client_user;
            this.textArea = textArea;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured, messege was not sent";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   textArea.append(messege);
            catch (IOException e)
                //error messege
                JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
    }

    Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
    I would say in your thread class do the following:
    MyConversationDialog dialog = new MyConversationDialog();
    while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   dialog.setVisible (true);
                   dialog.addMessage (message);
                }

  • Simple question about sockets and streams - please answer it!

    Hi
    I have a server socket and a client socket. Both are up and runing. But I'm having problems to send a string from the client and read only the four first bytes on the server. Please read the code and some other comments below:
    socket client:
    DataOutputStream out =
    new DataOutputStream(socket.getOutputStream());
    // read from keyboard input
    BufferedReader myinput =
    new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Type any 4 chars and [enter].");
    String any = myinput.readLine();
    out.writeBytes(any);
    out.flush();
    server socket:
    in = new DataInputStream(socket.getInputStream());
    byte[] id = new byte[4];
    in.read(id, 0, 4);
    System.out.print(new String(id));
    According to the code, it should read 4 bytes from the input stream (in.read(id, 0, 4)), but it displays only the first byte. For example, if I type "hello" on client, the serve should show "hell" but it shows just "h"
    Any ideias? Thanks!

    Hi,
    Check the Javadoc for 'in.read(id, 0, 4);' This reads up to 4 bytes and returns the number of bytes read. You need something along the lines of
    int count = 0;
    while (count < 4)
    count += in.read(id, count, 4-count);
    Roger

  • TCP socket and MDS/BES

    Hi All,
    We, in our app tried using the following statements by getting a reference from a blackberry document but the issue here is that following statement dint work.
    the connection opening statements are:
    1 socket://<ip> : <port>; // notice no deviceside param, on http://www.blackberry.com/knowledgecenterpublic/li​velink.exe/fetch/2000/348583/800451/800563/What_Is​...
    the following line is written.
    "If BlackBerry MDS is not available at the time of connection, the BlackBerry smartphone reverts to direct TCP".
    but on emulator itself this is not happening, above statement works only when MDS is running on my system.
    so my question is what will be the exact behaviour on device or on emulator
    if
    1 We provide deviceside param either TRUE or FALSE?
    2 We dint provide it all, like above?
    3 Is it carrier dependent?
    Please sort our my problem, as this is eating up our time.
    Thanks
    DC

    What happens if you call setTcpNoDelay(false) on that Socket you're using to send the data? That call would have the effect of instructing the networking layer to send data as soon as you have it rather than waiting for a certain occupancy in the buffer before transmitting. This is pretty much essential if you require any kind of interactivity in my experience, but it harms total throughput since the networking layer can't optimize by buffering your data.
    As was previously mentioned, flushing is likely to do the job in a cleaner fashion (write all your packets and then call flush to force the last one out). Any luck with that?

  • 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

  • P socket and upgradeability u101

    Just a few questions I hope someone outh there can answer.  I noticed that the U110 has a socket P.  I am wondering if anyone has done the research to figure out compatible processors for upgrading this model.  The other question is – is  there a BIOS update needed  or any other updates needed?

    jschell,
    Thank you for your response. Yes! I am catching exceptions but I am not getting any exceptions to catch. That's I had to change my design to Open and Close Client socket for every message I send which is NOT efficient. I would really like to have something like PING to improve the performance. Here's my code.
    while(true)
    deQueue the message from Queue......
    try {
    socket = new Socket(server, port);
    createLog.writeFile(" Connected with server " +
    socket.getInetAddress() +
    ":" + socket.getPort());
    conn = false;
    catch (ConnectException ce) {
    createLog.writeFile(" Client Socket " + ce.toString());
    //socket.close();
    //socket.wait(60);
    conn = true;
    returnFlag = false;
    catch (UnknownHostException e) {
    createLog.writeFile(e.toString());
    System.exit(ERROR);
    catch (IOException e) {
    createLog.writeFile(e.toString());
    System.exit(ERROR);
    try {
    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    output = new PrintWriter(socket.getOutputStream(),true);
    // get user input and transmit it to server
    lineToBeSent = msgText;
    // stop if input line is "."
    output.println(lineToBeSent);
    createLog.writeFile(lineToBeSent);
    //socket.wait(5);
    returnFlag = true;
    catch (IOException e) {
    createLog.writeFile(" Client Socket : " + e.toString());
    socket.close();
    returnFlag = false;
    catch (IllegalMonitorStateException le)
    createLog.writeFile(" Client Socket : Catching IllegalState Exception"+ le.toString());
    socket.close();
    createLog.writeFile(" Socket Expection : Closing Socket");
    returnFlag = true;
    // Closing Socket Connection at the end
    try{
    socket.close();
    createLog.writeFile(" Closing Socket ");
    catch(Exception ex)
    createLog.writeFile(" deQueque, Exception from " + ex.toString());
    returnFlag=false;
    }

  • Socket and Security Policy

    I've tried to set experiment with Socket communication in Flex, but I keep hitting problems. Approach 1: in a Flex web app, I load a crossdomain security policy from a server. I then open a socket and write a few bytes to the server. In my server, I do not get the expected output on the stream--in fact, I get nothing at all--until I close the Flex application, at which point I get a seemingly inifinite stream of the bytes '0xEFBFBF'. Here's a hexdump view of a fragment of the data Flash Player sends to the server after I close the Flex app:
    00000130  ef bf bf ef bf bf ef bf  bf ef bf bf ef bf bf ef  |................|
    00000140  bf bf ef bf bf ef bf bf  ef bf bf ef bf bf ef bf  |................|
    00000150  bf ef bf bf ef bf bf ef  bf bf ef bf bf ef bf bf  |................|
    Approach 2: I then tried it in air, but although the connection seems to initiate properly and I can go through the above trivial client-server interaction, after a few seconds, I get a SecurityErrorEvent. From what I've been able to follow of the docs, Air applications are trusted in this respect, and should not need to load security policy, right? I tried to add a call to Security.loadPolicy(), but it seems to be ignored. This is the message flow:
    Received [class Event] connect
    Received [class ProgressEvent] socketData
    Received [class Event] close
    Received [class SecurityErrorEvent] securityError
    Security error: Error #2048: Security sandbox violation: app:/main.swf cannot load data from localhost:5432.
    The Air version of my client code is below:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            var str:Socket;
            private function handleClick(e:Event):void {
                Security.loadPolicyFile("xmlsocket://localhost:2525");           
                str = new Socket('localhost', 5555);
                var message:String = 'hello';
                for (var i:int = 0; i < message.length; i++) {
                    str.writeByte(message.charCodeAt(i));               
                str.writeByte(0);
                str.flush();
                str.addEventListener(Event.ACTIVATE, handleEvent);
                str.addEventListener(Event.CLOSE, handleEvent);
                str.addEventListener(Event.CONNECT, handleEvent);
                str.addEventListener(Event.DEACTIVATE, handleEvent);
                str.addEventListener(IOErrorEvent.IO_ERROR, handleEvent);
                str.addEventListener(ProgressEvent.SOCKET_DATA, handleEvent);
                str.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleEvent);           
            private function handleEvent(e:Event):void {
                 trace("Received", Object(e).constructor, e.type);
                 if (e is ProgressEvent) {
                     var strBytes:Array = [];
                     while(str.bytesAvailable > 0) {
                         var byte:int = str.readByte();
                         strBytes.push(byte);
                     trace(String.fromCharCode.apply(null, strBytes));
                 } else if (e is SecurityErrorEvent) {
                     trace("Security error:", SecurityErrorEvent(e).text);
        ]]>
    </mx:Script>
    <mx:Button label="test" click="handleClick(event)"/>   
    </mx:WindowedApplication>
    The server is in Java and is as follows:
    import java.net.*;
    import java.io.*;
    public class DeadSimpleServer implements Runnable {
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                throw new Exception("Usage: DeadSimpleServer policy-port service-port");
            int policyPort = Integer.parseInt(args[0]);
            int servicePort = Integer.parseInt(args[1]);
            new Thread(new DeadSimpleServer(policyPort,
                                            "<?xml version=\"1.0\"?>\n" +
                                            "<cross-domain-policy>\n" +
                                            "<allow-access-from domain=\"*\" to-ports=\"" + servicePort + "\"/>\n" +
                                            "</cross-domain-policy>\n"
                       ).start();
            new Thread(new DeadSimpleServer(servicePort, "world")).start();
            while (true) Thread.sleep(1000);
        private int port;
        private String response;
        public DeadSimpleServer(int port, String response) {
            this.port = port;
            this.response = response;
        public String getName() {
            return DeadSimpleServer.class.getName() + ":" + port;
        public void run() {
            try {
                ServerSocket ss = new ServerSocket(port);
                while (true) {
                    Socket s = ss.accept();
                    System.out.println(getName() + " accepting connection to " + s.toString());
                    OutputStream outStr = s.getOutputStream();
                    InputStream inStr = s.getInputStream();
                    int character;
                    System.out.print(getName() + " received request: ");
                    while ((character = inStr.read()) != 0) {
                        System.out.print((char) character);
                    System.out.println();
                    Writer out = new OutputStreamWriter(outStr);
                    out.write(response);
                    System.out.println(getName() + " sent response: ");
                    System.out.println(response);
                    System.out.println(getName() + " closing connection");
                    out.flush();
                    out.close();
                    s.close();
            } catch (Exception e) {
                System.out.println(e);
    Am I missing something? From what I understand, either of these approaches should work, but I'm stuck with both. I have Flash Player 10,0,15,3 and am working with Flex / Air 3.0.0 under Linux.

    So... apparently, with the Air approach, this is what I was missing: http://www.ultrashock.com/forums/770036-post10.html
    It'd be nice if FlashPlayer gave us a nicer error here.
    I'm still trying to figure out what the heck is going on in the web app (i.e., non-Air Flex) example. If anyone has any suggestions, that would be very helpful.

  • Socket and keepalive

    How do I do keepalive with Flex sockets?

    Now this is client code. You should be having another piece of code that is
    listening on the IP, and port 8023. When you call socket.connect(ip, 8023); you
    connect to a machine running that piece of code typically called server. Tah
    code aknowledge the fact that you called connect and will send some answer back
    to you that you are connected. That answer will treigger your onConnect for
    which you registered with this line socket.addEventListener(Event.CONNECT,
    onConnect); Now you can send and recieve data.
    your onData will be called every time the application you connect to will send
    something to you.
    your onData should look something like this
    private function onData(event:ProgressEvent):void
                var data:ByteArray = readResponse();
                //do whatever you want with the bytes
    private function readResponse():ByteArray
                var byteArray:ByteArray = new ByteArray();
                socket.readBytes(byteArray, 0);   
                return byteArray;
    Your server will call you to ping it. So insetad of these lines
                //do whatever you want with the bytes
    you should read the bytes and somehow figure out that you need to ping. Then
    prepare a response message fluish the socket and wait.
    you should have a close handler also:
    socket.addEventListener(Event.CLOSE, closeHandler);
    private function closeHandler(event:Event):void
                trace("closeHandler: " + event);
                //if this code e4xecutes you are disconnected.
    http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_5 .html
    this also helps to get a better picture .
    C

  • Socket and ObjectOuputStream

    Hi
    I have a method
    private void createSocket() throws IOException {     
    socket = new Socket(IP, port);
    os = new ObjectOutputStream(socket.getOutputStream());
    is = new ObjectInputStream(socket.getInputStream());
    and have another method what write objects using the socket
    public void writeObject(Object obj) {
    try {
    os.flush();
    os.writeObject(obj);
    os.flush();
    obj2 = is.readObject();
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    when I call twice the method writeObject, my application throws
    java.net.SocketException: Software caused connection abort: socket write error
    What is the problem in my code?
    Gabo

    The problem is most likely on the server side. I'm guessing that the server is closing the connection before you can do the second read.

  • Sockets and TestNG

    This problem relates to Testing a client/server program that uses Sockets.
    I have some code which basically involves transmitting some Strings from client to server over sockets.
    The code worked fine when dealing with jEdit and terminals.
    I ran the Server and then had some main methods which I ran manually in the right order for each thing I wanted to send to the server.
    Now I have set the code up in Eclipse and have written some TestNG tests. The problem is that the server seems to block as soon as it is set up and no other tests get the chance to run, notably, those that are supposed to send the stuff to the server.
    I tried a few things. First I tried to get the tests to run in parallel. That didn't work. Secondly I put the tests in two test classes, that didn't work either.
    If anyone had any suggestions of how to deal with this I would be very grateful.
    Some of the code I have is as follows:
    This is my Server socket code:
    ServerSocket serverSocket = new ServerSocket(PORT) ;
    Socket socket = serverSocket.accept();
    BufferedReader incomingFileBuffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));This is my client code:
    socket = new Socket(HOST, PORT);
    PrintWriter toServer = new PrintWriter(socket.getOutputStream()) ;

    Your socket peers have to talk using some sort of protocol. The protocol might include sending a handshake packet and the size of your text file before actualy dumping that file to the socket stream. Then on the receiving end the application has better chances to distinguish between raw data you're sending through the socket.

  • Sockets and lockups in applets.

    I've handed this project in a while aog now, and it had partial functionality. I was however wondering why I came accross this same recurring problem?
    I believe i have set my loops in the correct places but my applet seems to 'lock up' after one result is returned.
    If anyone can shed some light on this (I think the applet is resetting the connection each time?) I would be most grateful.
    This is the server
    import java.io.*;
    import java.net.*;
    public  class  PizzaExpressServer {
         public static void main (String []args){
              try
                   ServerSocket   SS  =  new ServerSocket(6000);
                   Socket   sts  =  SS.accept();
                   DataInputStream isfc  =  new DataInputStream(sts.getInputStream());
                   DataOutputStream ostc  =  new DataOutputStream(sts.getOutputStream());
                   while(true) {
                        int select  =  isfc.readInt();
                        System.out.println("Selection received from client " + select);
                       double total = 0.0;
                    switch(select){
                    case 1: total += 2; break;
                        case 2: total += 3; break;
                        case 3: total += 4; break;
                        case 4: total += 5; break;
                        case 5: total += 0.5; break;
                        case 6: total += 0.5; break;
                        case 7: total += 0.5; break;
                        case 8: total += 0.5; break;
                        case 9: total += 0.5; break;
                        case 10: total = 0; break;
                        ostc.writeDouble(total);
                        ostc.flush();
                        System.out.println("Price of Pizza is: "  +  total);
    } catch (IOException  e) {
                   System.out.println(e);
    And here is the client...
    //<title> Pizza Express </title>
    //<applet code="PizzaExpress.class"
    //     width=300 height=200>
    //</applet>
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class PizzaExpress extends Applet implements ItemListener {
       private CheckboxGroup One;
       private Checkbox small, medium, large, Family, Ham, Pineapple, Chicken, Sweetcorn, ExtraChesse, Reset;
       private double total;
       private int selection;
       private TextField tf;
       Panel Top = new Panel();
       Panel Bottom = new Panel();
       public void init(){
        One = new CheckboxGroup();
         add (new Label(" Select pizza size   "));
         Panel Top = new Panel();
        Panel Bottom = new Panel();
         small = new Checkbox("Small", One, false);
         add(small);     
         small.addItemListener(this);
        medium = new Checkbox("Medium", One, false);
         add(medium);
         medium.addItemListener(this);
         large = new Checkbox("Large", One, false);
         add(large);
         large.addItemListener(this);
         Family = new Checkbox("Family", One, false);
         add(Family);          
         Family.addItemListener(this);
         Ham = new Checkbox("Ham");
         add(Ham);
         Ham.addItemListener(this);
         Pineapple = new Checkbox("Pineapple");
         add(Pineapple);
         Pineapple.addItemListener(this);
         Chicken = new Checkbox("Chicken");
         add(Chicken);
         Chicken.addItemListener(this);
         Sweetcorn = new Checkbox("Sweetcorn");
         add(Sweetcorn);
         Sweetcorn.addItemListener(this);
         ExtraChesse = new Checkbox("ExtraChesse");
         add(ExtraChesse);
         ExtraChesse.addItemListener(this);
         Reset = new Checkbox("Reset");
         add(Reset);
         Reset.addItemListener(this);
         tf = new TextField(30);
         add(tf);
        Top.add(small);
         Top.add(medium);
         Top.add(large);
         Top.add(Family);
         Bottom.add(Ham);
        Bottom.add(Pineapple);
        Bottom.add(Chicken);
        Bottom.add(Sweetcorn);
         Bottom.add(ExtraChesse);
         Bottom.add(tf);
         Bottom.add(Reset);
        add(Top);
         add(Bottom);
       public void itemStateChanged(ItemEvent e) {
          try
           Socket NS = new Socket(getCodeBase().getHost(), 6000);
           DataInputStream Dis = new DataInputStream(NS.getInputStream());
           DataOutputStream Dos = new DataOutputStream(NS.getOutputStream());
           if (e.getSource() == small){
              selection = 1;}
          if (e.getSource() == medium){
              selection += 2;}
          if (e.getSource() == large){
              selection += 3;}
          if (e.getSource() == Family){
              selection += 4;}
           if (e.getSource() == Ham){
              selection += 5;}
            if (e.getSource() == Pineapple){
              selection += 6;}
            if (e.getSource() == Chicken){
              selection += 7;}
           if (e.getSource() == Sweetcorn){
              selection += 8;}
           if (e.getSource() == ExtraChesse){
              selection += 9;}
            if (e.getSource() == Reset){
              selection = 10;}
          Dos.writeInt(selection);
           Dos.flush();
           total  =  Dis.readDouble();
           tf.setText("Pizza total is ?" + total);
           } catch (IOException  ex) {
                     System.out.println(ex);}
    }I've included some HTML in at the top for easy running.

    If your code hangs somewhere, find out where. Put in some debugging println()'s to zero in on the line where it hangs.
    Looking at the code quickly, one bug seems to be that you open sockets and streams and never close them. Do that in both the server and in the client.
    You probably want to put your accept() call inside the loop, and close the accepted socket after you are done.

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

  • Conflict between socket and RMI

    Hi
    I wrote a program in client-server using socket and it was fine. I also wrote a client-server program using RMI. Fine as well. But after I connected the client-server using socket (open socket, send-receive messages, close socket), then use RMI. I got java.rmi.NotBoundException.
    Would anyone have a look and provide your feedback please? Thanks.
    big J
    *****************this is Server.java ***************************
    package single;
    import java.io.*;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.net.*;
    import java.rmi.*;
    public class Server
    extends Thread {
    public static final int SOCKETPORT = 5555;
    private String serverName;
    public Server() throws IOException {
    System.out.println("*** socket opened ***");
    serverName = new String("localhost");
    ServerSocket serverSocket = new ServerSocket(SOCKETPORT);
    Socket socket = serverSocket.accept();
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(os), true);
    printWriter.println("from server");
    os.close();
    is.close();
    socket.close();
    System.out.println("*** socket closed ***");
    public void runServer() {
    System.out.println("*** start of run():RMI ***");
    System.setSecurityManager(new SecurityManager());
    try {
    RMIInterfaceImpl rMIInterfaceImpl = new RMIInterfaceImpl();
    Naming.bind("//" + serverName + ":9999/RMIInterface", rMIInterfaceImpl);
    catch (RemoteException ex) {
    catch (MalformedURLException ex) {
    catch (AlreadyBoundException ex) {
    System.out.println("*** end of run():RMI ***");
    public static void main(String args[]) throws Exception {
    Server server = new Server();
    server.runServer();
    ******************this is Client.java **************************
    package single;
    import java.io.*;
    import java.net.*;
    import java.rmi.Naming;
    public class Client {
    private String serverName;
    private final static int SOCKETPORT = 5555;
    public Client() throws IOException {
    serverName = new String("localhost");
    Socket socket = new Socket(serverName, SOCKETPORT);
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter=new PrintWriter(os, true);
    printWriter.println("from client");
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    is.close();
    os.close();
    socket.close();
    public void runClient() throws Exception {
    System.out.println("*** start of runClient():RMI ***");
    System.setSecurityManager(new SecurityManager());
    RMIInterface rMIInterfaceImpl = (RMIInterface) Naming.lookup(
    "//" + serverName + ":9999/RMIInterface");
    String str = rMIInterfaceImpl.print();
    System.out.println(str);
    rMIInterfaceImpl.serverSide();
    System.out.println("*** end of runClient():RMI ***");
    public static void main(String args[]) throws Exception {
    Client client = new Client();
    client.runClient();
    ***************** this is RMIInterface.java ***********************
    package single;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    interface RMIInterface
    extends Remote {
    String print() throws RemoteException;
    void serverSide() throws RemoteException;
    ********************* this is RMIInterfaceImpl.java ***************
    package single;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class RMIInterfaceImpl
    extends UnicastRemoteObject
    implements RMIInterface {
    public RMIInterfaceImpl() throws RemoteException {}
    public String print() {
    return new String("hello world");
    public void serverSide(){
    System.out.println("this should appear in serverside");

    I think you have a timing problem between your client and server. As soon as your client and server programs have finished their socket communication, they will both do their "runServer"/"runClient" methods. If the client attempts to lookup the server before the server has registered itself via Naming.bind(), I would expect that's why you're getting a NotBoundException in the client.
    You probably wouldn't use the design of your test client/server for something significant, but a quick and dirty way to make this work might be to have the client call Thread.sleep() for a few seconds before trying to do the lookup.

  • Problem with the socket and the standard output stream

    Hy, I have a little problem with a socket program. It has the server and the client. The problem is that the client at one point in the program, cannot print messages in the console.
    My program does the next: the server waits connections, when a client connects to it, the server gets outputstream to the socket and writes two strings on it. Meanwhile, the client gets the inputstream to the socket and reads on it with a loop the two strings written by the server . The strings are printed by the client in the console. The problem starts here; once the read strings are printed ,I mean, after the loop, there are other System.out.println in the client but the console doesnt print anything . It curious that only when I comment on the server code the line that says: "br.readLine()" just before the catch, the client prints all the System.out.println after the loop but why?
    Here is the code:
    Server code:
    public class MyServerSocket {
    public MyServerSocket() {
    try{
    ServerSocket server= new ServerSocket(2000);
    System.out.println("servidor iniciado");
    Socket client=server.accept();
    System.out.println("Client connected");
    OutputStream os=client.getOutputStream();
    PrintWriter pw= new PrintWriter(os);
    String cadena1="cadena1";
    String cadena2="cadena2";
    pw.println(cadena1);
    pw.println(cadena2);
    pw.flush();
    InputStream is=client.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br= new BufferedReader(isr);
    br.readLine(); //If a comment this line, the client prints after the loop, all the System.out....
    catch (IOException e) {
    // TODO: handle exception
    public static void main(String[] args) {
    new MyServerSocket
    Client code:
    public class MyClientSocket {
    public MyClientSocket () {
    try{
    Socket client= new Socket("localhost",2000);
    InputStream is=client.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br= new BufferedReader(isr);
    String read;
    while((read=br.readLine())!=null){
    System.out.println(read);
    //These messages are not printed unless I comment the line I talked about in the server code
    System.out.println("leido");
    System.out.println("hola");
    }catch (IOException e) {
    public static void main(String[] args) {
    new MyClientSocket
    }

    You are right but with this program the loop ends. As you see, the first class, the Server, writes to the socket one text file. The second class, the client, reads the text file in his socket written by the server and writes it to a file in his machine.
    NOTE: The loop in the client ends and the server doesnt make any close() socket or shutdownOutput() .
    public class ServidorSocketFicheromio {
         public ServidorSocketFicheromio() {
    try{
         ServerSocket servidor= new ServerSocket(2000);
         System.out.println("servidor iniciado");
         Socket cliente=servidor.accept();
         System.out.println("cliente conectado");
         OutputStream os=cliente.getOutputStream();
         PrintWriter pw= new PrintWriter(os);
         File f = new File("c:\\curso java\\DUDAS.TXT");
         FileReader fr= new FileReader(f);
         BufferedReader br= new BufferedReader(fr);
         String leido;
         while((leido=br.readLine())!=null){
              pw.println(leido);
         pw.flush();
         }catch (IOException e) {
         * @param args
         public static void main(String[] args) {
              new ServidorSocketFicheromio();
    public class ClienteSocketFicheromio {
         public ClienteSocketFicheromio() {
    try{
         Socket cliente= new Socket("localhost",2000);
         File f = new File("G:\\pepe.txt");
         FileWriter fw= new FileWriter(f);
         PrintWriter pw= new PrintWriter(fw);
         InputStream is=cliente.getInputStream();
         InputStreamReader isr= new InputStreamReader(is);
         BufferedReader br= new BufferedReader(isr);
         String leido;
         while((leido=br.readLine())!=null){
              pw.println(leido);
              System.out.println(leido);
              System.out.println("leido");
              System.out.println("hola");
              pw.flush();
         }catch (IOException e) {
         public static void main(String[] args) {
         new ClienteSocketFicheromio();/
    }

  • Problems with sockets and InputsStreams

    Hi,
    I ve this code:
    InputStream is = null;
    boolean ok=true;
    while(ok){
    //sc is an object instance of socketConnection
    is = sc.openInputStream();
    return this.parse(is);
    //is.close();
    return "";
    and this exception is produced:
    java.io.IOException: no more Input Streams available.
    This exception is produced in the line:
    is = sc.openInputStream();
    I m connecting to a server and this server sends data throw a socket... but the problem is that when i m reading from this socket and this socket doesn t have data in it...
    how could i solve this problem...?
    Thanks,
    Diego

    That would be the "real" code:
    public String process()throws IOException{
    InputStream is = null;
    is = sc.openInputStream();
    String result= this.parse(is);
    is.close();
    any suggestions?
    Thanks,
    Diego

Maybe you are looking for

  • WRT160N wont' recognize modem and other issues

    To prevent a wall of text from being even taller, here are the three topographies presented in some crude visuals: Default, Option "A" Better, Option "B" Optimal, Option "C" On second thought those images are pretty tall. That totally backfired. Enjo

  • Is the store down/dead?

    I can't download season passes, log in, nothing. On two separate machines I get the annoying "We're sorry, we cannot complete your request on the iTunes Store at this time." when I try anything... ugghghgh I can browse the store, preview things... Bu

  • Problem with Address Line 2 in Contacts

    I am currently syncing my contacts with my Yahoo mail.  The problem that I am having is that we live in an area where most people have an Address Line 2 (Usually their PO Box).  I am able to enter their PO Box into the Address Line 2 field in contact

  • How-to extend the Sales Order with the Project ID?

    Hello ByD Community, My problem is the following: I want to add an extension field to the Sales Order Header, which would be the Project ID assigned to this Sales Order. My use case only involve one Project ID per Sales Order, and the task will be th

  • Kdemod removed from pacman.conf but not from /var/lib/pacman

    Hello all I have been using kdemod repository for some time. Since I use Gnome I have removed all my kde/qt applications and I have removed kdemod repository from pacman.conf Is it normal to still have kdemod into /var/lib/pacman ? Can I safely remov