網絡編程已經成為一種時髦,以TCP/IP協議的網絡更為流行.自己編一個服務器與客戶機互相傳送消息的程序,以便增加自己網絡編程的經驗.下面我就介紹一下我編的程序.
首先介紹服務器程序:
1.創建一個名為"server"的項目,單文檔界面.
2.在servervIEw.h中加入代碼:
#include "winsock.h"
添加變量:
CSize sizeTotal;//控制滾動條
int count;//信息條數
CString m_data[1000];//信息存放
char Hostname[260];
char Hostaddress[20];//主機IP地址
SOCKET m_sock;
HANDLE m_hListenThread;//線程
BOOL m_bInitialized;//是否初始化
WSADATA WSAData;
BOOL flag;
SOCKADDR_IN saClnt;
int saClntLen;
BOOL Isconnect;//是否連接
3.在serverview.cpp中重載CServerVIEw()構造器,創建並綁定嵌套字:
CServerView::CServerVIEw()
{ // TODO: add construction code here
Isconnect=FALSE;
flag=FALSE;
sizeTotal.cy=350;
sizeTotal.cx=300;
m_hListenThread;
count=5;
int status;
WSADATA wsaData;
m_data[0]="initializing Windows Sockets DLL....";
if((status=WSAStartup(0x0101,&wsaData))==0)
{ m_data[0]+="Succeeded";
m_bInitialized=TRUE;
}
else
{ m_bInitialized=FALSE;
}
m_sock=socket(AF_INET,SOCK_DGRAM,0);
m_data[1]="Creating socket....";
if(m_sock==INVALID_SOCKET)
{ m_data[1]+="Failed";
}
m_data[1]+="Succeeded";
m_data[2]="Binding socket....";
sockaddr_in sa;
sa.sin_family=AF_INET;
sa.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
sa.sin_port=htons(5050);
if(bind(m_sock,(PSOCKADDR)&sa,
sizeof(sa))==SOCKET_ERROR)
{ m_data[2]+="Failed";
closesocket(m_sock);
}
m_data[2]+="Succeeded";
m_data[3]="Creating listener thread....";
unsigned long idThread;
m_hListenThread=CreateThread(NULL,0,
(LPTHREAD_START_ROUTINE)Listen,
(void *)this,0,&idThread);
if(m_hListenThread)
{ m_data[3]+="Succeeded";
m_data[4]+="Listening....";
}
else
m_data[4]+="Failed";
}
4.在析構函數中完成必需的清除操作:
CServerView::~CServerVIEw()
{ if(m_bInitialized)
WSACleanup();
closesocket(m_sock);
if(m_hListenThread)
::TerminateThread(m_hListenThread,0);
}
5.定褰郵蘸痛硐⒌南叱?
long WINAPI Listen(CServerView *pVIEw)
{ char msg[2000]="";
int nchar;
SOCKADDR_IN saClnt;
int saClntLen;
while(1)
{ saClntLen=sizeof(saClnt);
nchar=recvfrom(pVIEw- >m_sock,msg,
1024,0,(PSOCKADDR)&saClnt,&saClntLen);
if(nchar< 0)
{ pView- >m_data[pVIEw- >count++]+
="Error in recvfrom
";
pVIEw- >InvalidateRect(NULL);
}
else
{
switch(msg[0])
{
case ’A’:
wsprintf(msg,"A:ClIEnt from %s attached
",
inet_ntoa(saClnt.sin_addr));
pView- >m_data[pVIEw- >count++]=msg;
pV
[1] [2] [3] [4] 下一頁