服务端:
#include<stdio.h>
#include<Winsock2.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested,&wsaData);
if(err!=0)
{
return;
}
if(LOBYTE(wsaData.wVersion)!=1||
HIBYTE(wsaData.wVersion)!=1) {
WSACleanup();
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_DGRAM,0);//创建套接字
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
char recvBuf[100];
recvfrom(sockSrv,recvBuf,100,0,(SOCKADDR*)&addrClient,&len);//接收数据
printf(" %s\n",recvBuf);
closesocket(sockSrv);
WSACleanup();
}
客户端:
#include<stdio.h>
#include<Winsock2.h>
//调用套接字
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested,&wsaData);
if(err!=0)
{
return;
}
if(LOBYTE(wsaData.wVersion)!=1||
HIBYTE(wsaData.wVersion)!=1) {
WSACleanup();
return;
}
SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);//创建套接字
SOCKADDR_IN addrSrv;//定义一个地址结构体的变量
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
sendto(sockClient,"hello",strlen("hello")+1,0,
(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
closesocket(sockClient);
WSACleanup();
}
我用vc++6.0编译过是没错误的,但不知道为什么服务端一运行就有一大堆随机字!
而且当我运行客户端后,服务端又没受到数据!
请各位帮帮忙解析一下!万分感谢!!
[此贴子已经被作者于2007-9-23 16:34:49编辑过]