程序中写了两个类,CServer和CClent类,
分别是:
/**************CServer****************/
private:
void ServerInit();
public:
BOOL InitAndListen(HWND hwnd,UINT port);
public:
SOCKET m_hSocket; //socket 句柄
SOCKET m_connect;
sockaddr_in m_addr;
UINT m_uPort;
HWND m_hWnd;
/******************.cpp**************/
CServer::CServer()
{
}
CServer::~CServer()
{
WSAAsyncSelect(m_hSocket, m_hWnd, 0, 0);
}
BOOL CServer::InitAndListen(HWND hwnd,UINT port)
{
m_uPort=port;
m_hWnd=hwnd;
if(m_hSocket != NULL)
{
//如果已经创建了套接字先关闭原来的
closesocket(m_hSocket);
m_hSocket = NULL;
}
if(m_hSocket == NULL)
{
//创建新的套接字,这里是创建的流类型的套接字
m_hSocket = socket(AF_INET, SOCK_STREAM,0);
ASSERT(m_hSocket != NULL);
ServerInit();
}
m_addr.sin_family = AF_INET;
m_addr.sin_addr.S_un.S_addr = INADDR_ANY;
m_addr.sin_port = htons(m_uPort);
int ret = 0;
int error = 0;
//绑定一个套接字到本机的地址
ret = bind(m_hSocket, (LPSOCKADDR)&m_addr, sizeof(m_addr));
if(ret == SOCKET_ERROR)
{ //绑定错误
AfxMessageBox("已经建立服务器!");
return FALSE;
}
//开始一个侦听过程,等待客户的连接
ret = listen(m_hSocket, 5); //这里的第二个参数表示最多支持的客户连接数
if(ret == SOCKET_ERROR)
{ //listen失败
AfxMessageBox("监听失败!");
return FALSE;
}
return TRUE;
}
void CServer::ServerInit()
{
if(WSAAsyncSelect(m_hSocket, m_hWnd, SER_MESSAGE, FD_ACCEPT|FD_READ|FD_WRITE|FD_CLOSE)>0)
AfxMessageBox("选择错误");
}
/*****************CClent******************/
#include "winsock.h"
private:
void ClientInit();
public:
BOOL InitAndConnet(HWND hwnd,UINT port,CString m_strServer);
void GetString(CString & str);
void SendString(CString a);
public:
CString m_strServer;
SOCKET m_hSocket;
sockaddr_in m_addr;
UINT m_uPort;
HWND m_hWnd;
CClient::CClient()
{
m_hSocket =NULL;
}
CClient::~CClient()
{
}
BOOL CClient::InitAndConnet(HWND hwnd,UINT port,CString strserver)
{
m_hWnd=hwnd;
m_uPort=port;
m_strServer=strserver;
if(m_hSocket != NULL)
{
//如果原来打开这套接字先关闭
closesocket(m_hSocket);
m_hSocket = NULL;
}
if(m_hSocket == NULL)
{
//创建新的流套接字
m_hSocket = socket(AF_INET, SOCK_STREAM,0);
ASSERT(m_hSocket != NULL);
ClientInit();
}
//准备服务器的信息,这里需要指定服务器的地址
m_addr.sin_family = AF_INET;
m_addr.sin_addr.S_un.S_addr = inet_addr(m_strServer.GetBuffer(0));
m_addr.sin_port = htons(m_uPort); //改变端口号的数据格式
//这里主动连接服务器,该过程将等待一定时间
int ret = 0;
int error = 0;
ret = connect(m_hSocket, (LPSOCKADDR)&m_addr, sizeof(m_addr));
if(ret == SOCKET_ERROR)
{//连接失败
if(GetLastError()!=WSAEWOULDBLOCK)
{
AfxMessageBox(_T("请确认服务器确实已经打开并工作在同样的端口!"));
return FALSE;
}
}
return TRUE;
}
void CClient::SendString(CString a)
{
if(send(m_hSocket,a.GetBuffer(0),a.GetLength(),0)==SOCKET_ERROR)
{
AfxMessageBox("客户端发送数据错误");
}
}
void CClient::GetString(CString &str)
{
recv(m_hSocket,str.GetBuffer(0),1024,MSG_DONTROUTE);
}
void CClient::ClientInit()
{
if(WSAAsyncSelect(m_hSocket,m_hWnd,CLI_MESSAGE,FD_READ|FD_WRITE|FD_CLOSE|FD_CONNECT)>0)
{
AfxMessageBox("选择错误");
}
}
定义对象,调用函数就可以了