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 (SocketTimeou开发者_JAVA技巧tException 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?
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.
精彩评论