初学VC++,UDP通信,打算实现客户端和服务器端互发消息。
改程序是从一个最基本的程序改过来的,原来的功能只是客户端发送一条消息到服务器端,服务器打印显示就好了。现在要给服务器添加发送,给客户端添加接受,不成功。
代码如下:
服务器端:
// udpserver.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "winsock2.h" #define BUF_ZIZE 64 #include <iostream> using namespace std; #pragma comment(lib,"ws2_32.lib") int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsd; SOCKET sServer; SOCKET sClient; SOCKADDR_IN addrServ; SOCKADDR_IN addrClient; char buf[BUF_ZIZE]; int retVal; //初始化套接字动态库 if(WSAStartup(MAKEWORD(2,2),&wsd) != 0) { cout<<"WSAStartup error"<<endl; return 1; } //创建套接字 sServer = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); if(INVALID_SOCKET == sServer) { cout<<"socket error"<<endl; WSACleanup(); return -1; } //创建客户端套接字 sClient = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); if(INVALID_SOCKET == sClient) { cout<<"Client socket failed"<<endl; WSACleanup(); return -1; } //服务器套接字 addrServ.sin_addr.s_addr = INADDR_ANY; addrServ.sin_port = htons(4999); addrServ.sin_family = AF_INET; //绑定套接字 retVal = bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN)); if(retVal == SOCKET_ERROR) { cout<<"bind erroe"<<endl; WSACleanup(); return -1; } int len = sizeof(SOCKADDR); //开始等待客户端发来消息 recvfrom(sServer,buf,BUF_ZIZE,0,(SOCKADDR*)&addrClient,&len); cout<<buf<<endl; addrClient.sin_family = AF_INET; addrClient.sin_addr.s_addr = inet_addr("127.0.0.1"); addrClient.sin_port = htons((short)4999); //发送给客户端 ZeroMemory(buf,BUF_ZIZE); strcpy(buf,"知道了"); sendto(sClient,buf,BUF_ZIZE,0,(SOCKADDR*)&addrClient,sizeof(SOCKADDR)); system("pause"); closesocket(sServer); WSACleanup(); return 0; }
客户端:
// udpclient.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #define BUF_SIZE 64 #include "winsock2.h" #pragma comment(lib,"ws2_32.lib") #include<iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsd; SOCKET sHost; SOCKET sClient; SOCKADDR_IN servAddr; char buf[BUF_SIZE]; char cuf[BUF_SIZE]; int retVal; //初始化套接字动态库 if(WSAStartup(MAKEWORD(2,2), &wsd) != 0) { cout<<"WSAStartup failed"<<endl; return -1; } //创建套接字 sHost = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); if(INVALID_SOCKET == sHost) { cout<<"socket failed"<<endl; WSACleanup(); return -1; } //创建客户端套接字 sClient = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); if(INVALID_SOCKET == sClient) { cout<<"Client socket failed"<<endl; WSACleanup(); return -1; } //设置服务器地址 servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servAddr.sin_port = htons((short)4999); int nServAddlen = sizeof(servAddr); //发消息送到服务器 ZeroMemory(buf,BUF_SIZE); strcpy(buf,"快了"); sendto(sHost,buf,BUF_SIZE,0,(SOCKADDR*)&servAddr,sizeof(SOCKADDR)); int len = sizeof(SOCKADDR); //开始等待服务端发来消息 ZeroMemory(cuf,BUF_SIZE); recvfrom(sClient,cuf,BUF_SIZE,0,(SOCKADDR*)&servAddr,&len); cout<<cuf<<endl; system("pause"); //关闭退出 closesocket(sHost); WSACleanup(); return 0; }