udpServer.cc
#include "udpServer.hpp"
void Usage(std::string proc)
{
std::cout << "Usage: " << proc << " port" <<std::endl;
}
int main(int argc, char *argv[])
{
if(argc != 2){
Usage(argv[0]);
exit(1);
}
udpServer *up = new udpServer(atoi(argv[1]));
up->initServer();
up->start();
delete up;
}
udpServer.hpp
#pragma once
#include<iostream>
#include<string>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
class udpServer
{
private:
std::string ip;
int port;
int sock;
public:
udpServer(int _port=8080)
:port(_port)
{}
void initServer()
{
sock = socket(AF_INET,SOCK_DGRAM,0);
std:: cout <<"sock:"<< sock <<std:: endl;
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(port);
local.sin_addr.s_addr = INADDR_ANY;
if(bind(sock, (struct sockaddr*)& local,sizeof(local)) < 0)
{
std::cerr << "bind error!\n" << std::endl;
exit(1);
}
}
void start()
{
char msg[64];
for(;;){
msg[0] = '\0';
struct sockaddr_in end_point;
socklen_t len = sizeof(end_point);
ssize_t s = recvfrom(sock,msg,sizeof(msg)-1,0,\
(struct sockaddr*)&end_point,&len);
if(s > 0){
msg[s] = '\0';
std::cout << "client#" << msg <<std:: endl;
std::string echo_string = msg;
echo_string += " [server echo]";
sendto (sock, echo_string.c_str(),echo_string.size(),\
0,(struct sockaddr*)&end_point,len);
}
}
}
~udpServer()
{
close(sock);
}
};
udpClient.cc
#include "udpClient.hpp"
void Usage(std::string proc)
{
std::cout <<"Usage: "<< proc << " svr_ip svr_port" << std::endl;
}
int main(int argc, char *argv[])
{
if(argc != 3){
Usage(argv[0]);
exit(1);
}
udpClient uc(argv[1], atoi(argv[2]));
uc.initClient();
uc.start();
return 0;
}
客户端不需要bind,但是需要IP和port
- 在进行bind的时候,很容易冲突!客户端无法启动
- 客户端需要唯一性,但是不需要明确必须是哪个端口号
- 但是需要IP和port:client udp,recv 和send时,系统会自动进行ip和端口号绑定
udpClient.hpp
#pragma once
#include<iostream>
#include<string>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
class udpClient
{
private:
std::string ip;
int port;
int sock;
public:
udpClient(std::string _ip = "127.0.0.1",int _port=8080)
:ip(_ip),port(_port)
{}
void initClient()
{
sock = socket(AF_INET,SOCK_DGRAM,0);
std:: cout <<"sock:"<< sock <<std:: endl;
}
void start()
{
std::string msg;
struct sockaddr_in peer;
peer.sin_family = AF_INET;
peer.sin_port = htons(port);
peer.sin_addr.s_addr = inet_addr(ip.c_str());
for(;;){
std :: cout << "Please Enter# ";
std :: cin >> msg;
if(msg == "quit")
{
break;
}
sendto(sock , msg.c_str(),msg.size(),0,(struct sockaddr*)& peer,sizeof(peer) );
char echo[128];
ssize_t s = recvfrom(sock,echo,sizeof(echo)-1, 0,nullptr,nullptr);
if(s>0)
{
echo[s] = 0;
std::cout << "server#" << echo << std::endl;
}
}
}
~udpClient()
{
close(sock);
}
};
|