WinSock网络程序

这是一个WinSock网络程序的基本步骤:
建立一个聊天的例子(TCP/IP)
server:
 1初始化socket库
 WSADATA wsaData;
 WORD version = MAKEWORD(2, 0);
 int ret = WSAStartup(version, &wsaData);
 if(ret != 0)
 {
  TRACE("Initilize Error!/n");  //初始化失败
  AfxMessageBox("Failed in initial socket");
 }
 2创建套接字
  m_hSocket = socket(AF_INET, SOCK_STREAM,0);
  这里选择异步方式
  WSAAsyncSelect(m_hSocket, m_hWnd, SER_MESSAGE, FD_ACCEPT|FD_READ|FD_WRITE|FD_CLOSE)
 3绑定到本机地址
 bind(m_hSocket, (LPSOCKADDR)&m_addr, sizeof(m_addr));
 4开始侦听
 listen(m_hSocket, 5);   //这里的第二个参数表示最多支持的客户连接数
 5写消息函数
 LRESULT OnServerMessage(WPARAM wParam, LPARAM lParam)
{

 SOCKET socket,ts;
 switch(lParam)
 {
 case FD_ACCEPT:
 socket= accept(m_hSocket,NULL,NULL);
 return 0;
 case FD_READ:
 len=recv(socket,s,1024,0);
        return 0;
 case FD_WRITE:
 return 0;
 case FD_CLOSE:
 return 0;
 default:
 return 0;
 }
}
6写发送信息函数
send(socket,Buffer,GetLength(),0);


Client:
1 创建socket
m_hSocket = socket(AF_INET, SOCK_STREAM,0);
WSAAsyncSelect(m_hSocket,m_hWnd,CLI_MESSAGE,FD_READ|FD_WRITE|FD_CLOSE|FD_CONNECT)这里选择异步
2 设定服务器地址信息
3 连接服务器
  connect(m_hSocket, (LPSOCKADDR)&m_addr, sizeof(m_addr));
4 写消息函数
LRESULT OnClientMessage(WPARAM wParam, LPARAM lParam)
{
 switch(lParam)
 {
 case FD_CONNECT:
 len=GetLastError();
 if(len!=0)
 {
 AfxMessageBox("Error in Connecting");
 }
 else
 {
        m_sShowText="Having connected to server!/n";
 GetDlgItem(IDC_SHOWTEXT)->SetWindowText(m_sShowText);
 }
 return 0;
 case FD_READ:
 len=recv(m_client.m_hSocket,s,1024,0);
 return 0;
 case FD_WRITE:
 return 0;
 case FD_CLOSE:
 return 0;
 default:
 return 0;
 }
}

5 发送消息
send(m_hSocket,GetBuffer(0),GetLength(),0)


qq:275554175
email:[email protected]

 


你可能感兴趣的:(网络,socket,Stream,server,服务器,null)