midhunhk
midhunhk

Reputation: 5554

How to write data to Socket opened by Flex from Java Server

Ok, basically my Flex app will open up a socket and listen on it. My java program will write some string to this port.

My AS3 code is

        private function onRecvClick():void
        {
            var host:String = "localhost"; 
            var port:int = 9090;

            var socket:Socket = new Socket(host, port);
            socket.addEventListener(Event.CONNECT, onConnect);
            socket.addEventListener(DataEvent.DATA, onData);
            socket.connect(host, port);
        }

And my Java code is :

 private ClientSocket()
{
    try
    {
        String  host    =   "localhost";
        int     port    =   9090;

        Socket socket = openSocket(host, port);

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write("HelloTest");
        writer.flush();

    }
    catch (Exception e)
    {
        System.out.println(e);
    }
}

private Socket openSocket(String server, int port) throws Exception
{
  Socket socket;

  // create a socket with a timeout
  try
  {
    InetAddress inteAddress = InetAddress.getByName(server);
    SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);

    // create a socket
    socket = new Socket();

    // this method will block no more than timeout ms.
    int timeoutInMs = 10*1000;   // 10 seconds
    socket.connect(socketAddress, timeoutInMs);

    return socket;
  } 
  catch (SocketTimeoutException ste) 
  {
    System.err.println("Timed out waiting for the socket.");
    ste.printStackTrace();
    throw ste;
  }
}

While trying to write to the socket, i am getting this java.net.ConnectException: Connection refused: connect. Funny thing is that the socket in Flex doesn't seem to dispatch any events, is it normal for that to happen?

Upvotes: 1

Views: 1129

Answers (1)

Mat
Mat

Reputation: 206879

Unless I'm misreading the docs completely, both flash.net.Socket and java.net.Socket are client sockets.

You need one side to be a server socket to be able to connect them together.

For the server side in Java, look at this walkthrough: Socket Communications.

Upvotes: 4

Related Questions