分类: LINUX
2011-04-15 17:39:30
在这个程序中,将两个工程添加到一个工作区。同时还要链接一个ws2_32.lib的库文件。
可以在VC++的Setting设置中加入,也可以在文件中导入#pragma comment(lib,"ws2_32")
服务器端编程的步骤:
1:加载套接字库,创建套接字(WSAStartup()/socket());
2:绑定套接字到一个IP地址和一个端口上(bind());
3:等待和接收数据(sendto()/recvfrom());
4:关闭套接字,关闭加载的套接字库(closesocket()/WSACleanup())。
服务器端代码如下:
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
void main()
{
SOCKET socket1;
//InitWinsock();
WSADATA wsaData;
int iErrorCode;
if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL
{
printf("Winsock无法初始化!\n");
WSACleanup();
return;
}
printf("服务器开始创建SOCKET。\n");
struct sockaddr_in local;
struct sockaddr_in from;
int fromlen =sizeof(from);
local.sin_family=AF_INET;
local.sin_port=htons(27015); ///监听端口
local.sin_addr.s_addr=INADDR_ANY; ///本机
socket1=socket(AF_INET,SOCK_DGRAM,0);
bind(socket1,(struct sockaddr*)&local,sizeof(local));
while (1)
{
char buffer[1024]="\0";
printf("waiting for message from others-------------\n");
if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
{
printf("Received datagram from %s--%s\n",inet_ntoa(from.sin_addr),buffer);
////给cilent发信息
sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,fromlen);
}
//Sleep(1000);
}
closesocket(socket1);
}
对于基于UDP的socket客户端来说,要进行如下步骤:
1:创建一个套接字(socket);
2:向服务器发送数据(sendto);
3:关闭套接字;
代码如下:
#include
#include
#pragma comment(lib,"ws2_32.lib")
void main()
{
SOCKET socket1;
//InitWinsock();
WSADATA wsaData;
int iErrorCode;
if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL
{
printf("Winsock无法初始化!\n");
WSACleanup();
return;
}
printf("服务器开始创建SOCKET。\n");
struct sockaddr_in server;
int len =sizeof(server);
server.sin_family=AF_INET;
server.sin_port=htons(27015); ///server的监听端口
server.sin_addr.s_addr=inet_addr("221.223.16.32"); ///server的地址
socket1=socket(AF_INET,SOCK_DGRAM,0);
while (1)
{
char buffer[1024]="\0";
printf("input message\n");
scanf("%s",buffer);
// printf("%s",buffer);
if (strcmp(buffer,"bye")==0)
{
printf("退出!\n");
Sleep(100);
closesocket(socket1);
break;
}
if (sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,len)!=SOCKET_ERROR)
{
//printf("sending..\n");
Sleep(100);
if (recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,&len) != SOCKET_ERROR)
printf("rece from server:%s\n",buffer);
}
}
closesocket(socket1);
}
注意:编程中启动服务端程序时,如果直接中断,没有等待出现。可能是端口绑定出现错误。解决方法:使用一个新的端口,给临时分配端口一般在1024~5000之间。大于5000的端口号是为其他服务预留。
内容来源:http://hi.baidu.com/zhaquanmin/blog/item/1c4cc55daf1fd34afbf2c0fc.html