利用Socket实现C++与Flex通信

一、C++服务器端

(用的是Visual Studio 20080503的应该也可以,VC++的可能需要稍微改动))

代码如下:

#include <winsock2.h>

#include <stdio.h>

#include <windows.h>

#include <iostream>

using namespace std;

#pragma comment(lib,"ws2_32.lib")

 

void main(){ 

 WORD wVersionRequested;

 WSADATA wsaData;

 int err;

 short port=1300;//端口号

 

 wVersionRequested = MAKEWORD( 1, 1 );

 

 err = WSAStartup( wVersionRequested, &wsaData );//初始化套接字

 if ( err != 0 )

 {

    return;

 }

 

 if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 )

 {

    WSACleanup( );

    return;

 }

 

 SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);//创建套接字

 SOCKET sockConn;//用来和客户端通信的套接字

 

 SOCKADDR_IN addrSrv;//用来和客户端通信的套接字地址

 

 addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);

 addrSrv.sin_family=AF_INET;

 addrSrv.sin_port=htons(port);

 

 bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));//绑定端口

 

 listen(sockSrv,5);//侦听

 

printf("Server %d is listening......\n",port);

 

 SOCKADDR_IN addrClient;

 

 int len=sizeof(SOCKADDR);

 

char buf[4096];//接收的数据

char rbuf[100]="成功";//返回的数据

 

 while(1)

 {

        //接受连接

         sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);

         printf("Accept connection from %s\n",inet_ntoa(addrClient.sin_addr));

 

         //接收数据

         int bytes;

         if((bytes=recv(sockConn,buf,sizeof(buf),0))==SOCKET_ERROR){

              printf("接收数据失败!\n");

              exit(-1);

         }

         buf[bytes]='\0';

         printf("Message from %s: %s\n",inet_ntoa(addrClient.sin_addr),buf);

 

         //发送数据

        if(send(sockConn,rbuf,strlen(rbuf)+1,0)==SOCKET_ERROR){

              printf("发送数据失败!");

              exit(-1);

         }

        printf("Message to %s: %s\n",inet_ntoa(addrClient.sin_addr),rbuf);

 

        //清理套接字占用的资源

        closesocket(sockConn);

 }

 

 

}

 

运行效果如下:

二、Flex客户端(Flex Builder

代码如下

<?xml version="1.0" encoding="utf-8"?>

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"

     creationComplete="initApp();">

        <mx:Script>

        <![CDATA[

            import flash.net.Socket;

            private var socket:Socket;

            private function initApp():void

            {

             

            }

           

            private function StartTest():void

            {         

              socket = new Socket("127.0.0.1",1300);     

                socket.addEventListener(Event.CONNECT, connectHandler);

                socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);

            }

            private function CloseTest():void

            {   

                if(socket!=null && socket.connected)

                {

                    trace("socket.connected:"+socket.connected);

                    socket.close();

                    trace("socket.connected:"+socket.connected);

                }

            }

            private function connectHandler(event:Event):void

            {

                trace("connectHandler: " + event);

                socket.writeMultiByte(SendStr.text,"GB2312");               

                socket.flush();

            }

            private function socketDataHandler(event:ProgressEvent):void

            {

                trace("socketDataHandler: " + event);

                var str:String=socket.readMultiByte(socket.bytesAvailable,"GB2312");

                ReceiveStr.text = str;

            }

        ]]>

    </mx:Script>

 

        <mx:Text text="发送" y="11" x="18" fontWeight="bold" color="#ffffff"/>

        <mx:TextArea id="ReceiveStr" x="53" y="68"/>

        <mx:Text text="接收" y="69" x="18" fontWeight="bold" color="#ffffff"/>

        <mx:TextArea id="SendStr" y="10" x="53"/>       

        <mx:Button label="Start" click="StartTest()" x="53" y="120"/>

        <mx:Button label="Close" click="CloseTest()" x="126" y="120"/>

</mx:WindowedApplication>

三、运行

先运行C++服务器端,再运行Flex客户端,成功后如下图所示

 

转载于:https://www.cnblogs.com/anhuizhxd/archive/2009/03/14/Cplusplus001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值