客户端:
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);
}