[AS/FLEX]
Flex AS3与Java的Socket通信
新建flash文件
:SocketExample.fla
添加按钮:btnSend
修改文档
类为:SocketExample
新建AS3文件:SocketExample.as
01.
package
{
02.
import
flash.display.Sprite;
03.
import
flash.events.*;
04.
import
flash.net.Socket;
05.
06.
public
class
SocketExample
extends
Sprite {
07.
08.
private
var socket:Socket;
09.
10.
public
function
SocketExample( ) {
11.
socket =
new
Socket( );
12.
13.
// Add an event listener to be notified when the
connection
14.
// is made
15.
socket.addEventListener(
Event.CONNECT, onConnect );
16.
17.
// Listen for when data is received from the socket
server
18.
socket.addEventListener(
ProgressEvent.SOCKET_DATA, onSocketData );
19.
20.
//var btnSend:Button = new Button();
21.
btnSend.label
=
"Send Data"
;
22.
btnSend.emphasized
=
true
;
23.
btnSend.width
=
150
;
24.
btnSend.move(
20
,
20
);
25.
addChild(btnSend);
26.
27.
btnSend.addEventListener(MouseEvent.CLICK,
sendData);
28.
}
29.
30.
private
function sendData(
event:Event ) {
31.
32.
if
(!socket.connected) {
33.
34.
// Connect to the server
35.
socket.connect(
"192.168.2.103"
,
5678
);
36.
}
37.
38.
trace(
"send..."
);
39.
socket.writeUTFBytes(
"example\n"
);
40.
socket.flush();
41.
42.
}
43.
44.
private
function onConnect(
event:Event ):
void
{
45.
trace(
"The socket is now connected..."
);
46.
}
47.
48.
private
function
onSocketData( eventrogressEvent ):
void
{
49.
trace(
"Socket received "
+
socket.bytesAvailable +
" byte(s) of data:"
);
50.
51.
trace(socket.readMultiByte(socket.bytesAvailable,
"UTF-8"
));
52.
}
53.
54.
55.
}
56.
}
Java
服务器
端:
MyServer
.java
01.
import
java.io.*;
02.
import
java.net.*;
03.
04.
public
class
MyServer {
05.
public
static
void
main(String[] args)
throws
IOException{
06.
ServerSocket
server=
new
ServerSocket(
5678
);
07.
08.
while
(
true
) {
09.
Socket
client=server.accept();
10.
BufferedReader
in=
new