用VC6的Socket收发数据,触发事件,从CAsynySocket类派生,将其打包成一个类

 

客户端:

class CClientSocket : public CAsyncSocket

在主对话框上加个按钮,在按钮函数中:

void CClientDlg::OnButtonConnect() //连接服务端
{
 // TODO: Add your control notification handler code here
 
 clientSocket.Create();//调用Create
 clientSocket.Connect("127.0.0.1",8000);//连接服务器IP的指定端口口
 clientSocket.AsyncSelect(FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT|FD_CLOSE);//如果要测试,可多注册几个事件,如果只用于发送,不需注册任何事件
 

 

}

void CClientDlg::OnButtonSend()
{
 // TODO: Add your control notification handler code here
 char buf[1024];
 strcpy(buf,"打倒小日本");
 clientSocket.Send(buf,sizeof(buf));
}

 

 

服务端:

服务端需要两个套接字,一个用于监听,另一个用于收发数据

这里只用于接收数据

派生两个类

class CServerSocket : public CAsyncSocket//

用于监听,所以要注册的事件为OnAccept,当收到连接请求时会执行


{
// Attributes
public:

 CDataSocket connectSocket;//用于接收信息的套接字,所以需注册这个类的FD_WRITE|FD_READ事件,注意不要注册到用于监听的类上,否则收不到数据

 

 

void CServerSocket::OnAccept(int nErrorCode) //发现有连接请求,用Accept接受连接,同时创建用于收发数据的Socket对象
{
 // TODO: Add your specialized code here and/or call the base class
 //AfxMessageBox("有连接请求");
 this->Accept(connectSocket);//connectSocket用于接收数据,connectSocket所属类的FD_WRITET FD_READ已注册
 connectSocket.AsyncSelect(FD_WRITE|FD_READ);
 CAsyncSocket::OnAccept(nErrorCode);
}

void CDataSocket::OnReceive(int nErrorCode)
{
 // TODO: Add your specialized code here and/or call the base class
 char buf[1024];
 int i = Receive(buf,1024);
 buf[i]=NULL;
 CString str;
 str=buf;
 AfxMessageBox(str); 
 CAsyncSocket::OnReceive(nErrorCode);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值