如何使用socket连接客户端和服务器?

时间:2015-09-24 04:13:28

标签: sockets client-server flash-builder actionscript-3

如何在ActionScript 3上实际运行此客户端/服务器项目?我使用的是flashbuilder。我不确定我是否做了正确的事情,我做了一个新的移动项目并为我的客户输入代码:

public class client extends Sprite
{
    private var socket:Socket;
    private var IP:String = "127.0.0.1";

    public function client()
    {
        super();

        socket = new Socket();
        socket.addEventListener(Event.CONNECT, onConnected);
        socket.connect(IP, 5555);
    }

    protected function onConnected(event:Event):void
    {
        socket.writeUTFBytes("communication between Sockets (Client socket and server socket)");
        socket.flush();
    }
}

然后我在包中创建了一个新类,其中包含客户端类(如上所述)并将其作为服务器类放入:

public class NewSocketServerTest extends Sprite
{
    private var serverSocket:ServerSocket = new ServerSocket();
    private var clientSocket:Socket;

    private var txt:TextField;
    public function NewSocketServerTest()
    {
        createUI();
        serverSocket.bind(5555);
        serverSocket.addEventListener(ServerSocketConnectEvent.CONNECT, onConnected);
        serverSocket.listen();
    }

    protected function onConnected(event:ServerSocketConnectEvent):void
    {
        txt.appendText("This is a demonstration of \n" );
        clientSocket = event.socket;
        clientSocket.addEventListener(ProgressEvent.SOCKET_DATA, onDataHandler);
    }       

    protected function onDataHandler(event:ProgressEvent):void
    {
        var str:String = clientSocket.readUTFBytes(clientSocket.bytesAvailable);
        txt.appendText(str);
    }

    private function createUI():void
    {
        txt = new TextField();
        txt.width=400;
        txt.height=400;
        txt.appendText("Hello! \n");
        addChild(txt);
    }
}

当我尝试在模拟器中运行时,它只是一个白色的屏幕,而且我不确定我做错了什么。

1 个答案:

答案 0 :(得分:0)

尝试指定serverSocket主机名。

tokens