我自己简单的写的,是从我的一个用MFC做的程序里面剪出来的,不了解的地方可以来问我,其实我也是刚开始编网络程序
我的QQ:531119186
(1)服务端
SOCKET Server;
struct sockaddr_in Cli;
char buf[50]="你好,我是服务端!";
char Revdata[50];
CString Status;
while(1)
{
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
MessageBox("socket 创建失败!","",MB_OK|MB_ICONERROR);
}
else {
Status.Format("socket创建成功!\r\n");
//SetDlgItemText(IDC_EDIT1,Status);
m_status.ReplaceSel(Status);
UpdateData(FALSE);
}
Server=socket(AF_INET,SOCK_STREAM,0);
Cli.sin_family=AF_INET;
Cli.sin_port=htons(DEFAULT_PORT);
Cli.sin_addr.s_addr=htonl(INADDR_ANY);
//Cli.sin_addr.s_addr=inet_addr("192.18.109.6");
if(bind(Server,(struct sockaddr*)&Cli,sizeof(Cli))==SOCKET_ERROR)
{
MessageBox("绑定本地地址失败!","反馈信息",MB_OK|MB_ICONERROR);
return ;
}
else {
Status="成功绑定本地地址!\r\n";
//SetDlgItemText(IDC_EDIT1,Status);
m_status.ReplaceSel(Status);
UpdateData(TRUE);
}
sListen=listen(Server,5);
if(sListen==SOCKET_ERROR)
{
MessageBox("侦听失败!","",MB_OK|MB_ICONINFORMATION);
return ;
}
else {
Status="服务端已经处于监听状态...\r\n";
//SetDlgItemText(IDC_EDIT1,Status);
m_status.ReplaceSel(Status);
//Sleep(100);
UpdateData(TRUE);
}
int sCli=sizeof(Cli);
SOCKET sAccept=accept(Server,(struct sockaddr*)&Cli,&sCli);
if(sAccept==INVALID_SOCKET)
{
Status="服务端接收失败!\r\n";
//SetDlgItemText(IDC_EDIT1,Status);
m_status.ReplaceSel(Status);
UpdateData(TRUE);
}
else
{
Status="连接客户端成功!\r\n";
CString IP;
IP.Format("有客户机已连接,对方IP:%s",inet_ntoa(Cli.sin_addr));
MessageBox(IP,"反馈消息",MB_OK|MB_ICONINFORMATION);
//SetDlgItemText(IDC_EDIT1,Status);
if(send(sAccept,buf,sizeof(buf),0)==SOCKET_ERROR)
{
Status="服务端发送数据失败!\r\n";
//SetDlgItemText(IDC_EDIT1,Status);
m_status.ReplaceSel(Status);
UpdateData(TRUE);
}
else
{
Status="服务端成功发送数据!\r\n";
//SetDlgItemText(IDC_EDIT1,Status);
m_status.ReplaceSel(Status);
UpdateData(TRUE);
}
closesocket(sAccept);
}
closesocket(sListen);
WSACleanup();
}
(1)客户端
SOCKET Client;
struct sockaddr_in Sev;
char buf[50];
memset(buf,'\0',sizeof(buf));
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
MessageBox("socket创建失败!","反馈信息",MB_OK|MB_ICONINFORMATION);
}
Client=socket(AF_INET,SOCK_STREAM,0);
Sev.sin_family=AF_INET;
Sev.sin_port=htons(DEFAULT_PORT);
Sev.sin_addr.s_addr=inet_addr("192.168.109.6");
//Sev.sin_addr.s_addr=htonl(INADDR_ANY);
int sConnect;
sConnect=connect(Client,(struct sockaddr*)&Sev,sizeof(Sev));
if(sConnect==SOCKET_ERROR)
{
MessageBox("连接服务端失败!","反馈信息",MB_OK|MB_ICONINFORMATION);
return ;
}
else
{
MessageBox("连接服务端成功!","反馈信息",MB_OK|MB_ICONINFORMATION);
}
if(recv(Client,buf,sizeof(buf),0)==SOCKET_ERROR)
{
MessageBox("接收失败!","反馈信息",MB_OK|MB_ICONINFORMATION);
return ;
}
else
{MessageBox("接收成功!","反馈信息",MB_OK|MB_ICONINFORMATION);
SetDlgItemText(IDC_EDIT1,buf);
}
closesocket(Client);
WSACleanup();
[此贴子已经被作者于2007-1-10 15:14:31编辑过]