一个菜到家的问题[关于socket的cs模型]
谁能给我一个multi-client,single-server的模型啊?
只要源代码,不要文章路径。
只要windows模型,谢绝unix模型。
可能的话,最好给出来console和windows模型
问题点数:0、回复次数:4Top
1 楼rockersz(世上的无奈需要我去忍耐...)回复于 2003-11-03 14:45:08 得分 0
我有,但代码很多,不好帖, 很多网站有这样的例子,比如www.codeproject.com, www.vckbase.comTop
2 楼Raxxxer(Jasmine Hellstorm)回复于 2003-11-03 16:36:38 得分 0
那说说机理可以吗?Top
3 楼postform999(真水无香)回复于 2003-11-03 16:46:27 得分 0
比较简单的,在服务器端打开并监听一个端口,如
m_sock.Create(1234,SOCK_STREAM,FD_ACCEPT);
//创建在本机ip上1234端口的tcp连接用于侦听。
m_sock.Listen(1);//开始侦听。
在ClistenSock类中声明ClistenSock类的指针m_psock。
重载ClistenSock的OnAccept函数如下:
void CListenSock::OnAccept(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
CClientSock* psock=new CClientSock;
Accept(*psock);//收到一个连接请求,创建新的连接进行通信
psock->AsyncSelect(FD_READ);//提请一个读操作,读取客户端的信息
m_psock=psock;
CAsyncSocket::OnAccept(nErrorCode);
}
然后收到客户端请求以后就建立连接通信
重载ClisntSock的OnReceive()和OnSend()函数如下:
void CClientSock::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
Receive(buff,1024,0);//接收客户端的信息
AsyncSelect(FD_WRITE);//提请一个发送操作,向客户端发送消息。
CAsyncSocket::OnReceive(nErrorCode);
}
void CClientSock::OnSend(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
int len=strlen(buff);
Send(buff,len,0);
Close();//发送完毕,关闭本次连接。
CAsyncSocket::OnSend(nErrorCode);
}
服务器程序实现简单的转发功能,把客户端发来的消息发回客户端。
关于客户端:
客户端程序需要一个新类CclientSock。重载OnReceice()和OnSend()函数。假设客户端程序是一个dialog based,添加一个按钮(连接和发送),部分实现代码如下:
void CClientDlg::OnButton1()
{
// TODO: Add your control notification handler code here
m_sock.Create();
m_sock.Connect("61.163.234.190",1234);
m_sock.AsyncSelect(FD_WRITE);//提请一个发送操作,向服务器发送数据
}
void CSock::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
char buff[255];
memset(buff,’0’,255);
Receive(buff,255);//接收数据
AfxMessageBox(buff);//回显
Close();//关闭连接
CAsyncSocket::OnReceive(nErrorCode);
}
void CSock::OnSend(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
Send("hello",6);
AsyncSelect(FD_READ);
CAsyncSocket::OnSend(nErrorCode);
}
简单客户端程序编写完毕。(程序来自www.vccode.com)Top
4 楼Raxxxer(Jasmine Hellstorm)回复于 2003-11-04 21:07:12 得分 0
O M G
I dont like MFC
would there anyone give me some sdk code?
thxTop




