在上一篇随笔中,对Winsock中基于tcp面向连接的Server和Client通信进行了说明,但是,Winsock中,Server和Client间还可以通过无连接通信,也就是采用UDP协议。。

因此,这一篇随笔也简单的列举基于UDP的Server和Client的实现。。

和基于TCP的实现相比,其主要的不同点包括:

①接收端(简单地说就是服务器)/发送端(简单地说就是客户端)在创建Socket时候,参数要选择SOCK_DGRAM, IPPROTO_UDP;

②接收端不需要调用listen和accept函数,而是通过recvfrom/WSArecvfrom函数接收数据报;

③发送端通过sendto/WSAsendto接收数据报;

接收端和发送端的代码如下:

 #include"winsock2.h"
#include<iostream>
using namespace std;
//This line is very important #pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsaData;
SOCKET ReceivingSocket;
SOCKADDR_IN ReceiverAddr;
int Port = ;
char ReceiveBuf[];
int BufLength = ;
SOCKADDR_IN SenderAddr;
int SenderAddrSize = sizeof(SenderAddr);
int Ret; if ((Ret = WSAStartup(MAKEWORD(,), &wsaData)) != )
{
cout<<"WSAStartup failed with error "<<Ret<<endl;
//here no WSACleanup,because we do not create anything;
return -;
} // Create a new socket to listening for client connections.
//Note the difference with TCP
ReceivingSocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if ( INVALID_SOCKET == ReceivingSocket)
{
cout<<"Socket failed with error "<<WSAGetLastError()<<endl;
WSACleanup();
return -;
} ReceiverAddr.sin_family = AF_INET;
ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
ReceiverAddr.sin_port = htons(Port); //to bind
if (bind(ReceivingSocket, (SOCKADDR *)&ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR)
{
cout<<"Binding failed with error "<<WSAGetLastError()<<endl;
closesocket(ReceivingSocket);
WSACleanup();
return -;
} // Listen for client connections. We used a backlog of 5 which is
// normal for many applications. cout<<"** We are ready to receive 1 datagram from any interface on port "<<Port<<"**"<<endl; //accep a connection when one arrives cout<<"** We are waiting for data...**\n";
//SenderAddrSize = sizeof(SenderAddr);
Ret = recvfrom(ReceivingSocket,ReceiveBuf,BufLength,,(SOCKADDR *)&SenderAddr,&SenderAddrSize);
if (SOCKET_ERROR == Ret)
{
cout<<"Recvfrom failed with error "<<WSAGetLastError()<<endl;
closesocket(ReceivingSocket);
WSACleanup();
return -;
}
cout<<"**We have successfully recieve "<<Ret<<" Byte(s) data!**\n"; cout<<"**We are going to close the client connection...**\n"; closesocket(ReceivingSocket);
WSACleanup(); return ;
}

Receiver Code

 #include"winsock2.h"
#include<iostream>
#include <time.h>
using namespace std;
//This line is very important #pragma comment(lib,"ws2_32.lib")
int main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET SendingSocket;
SOCKADDR_IN ReceiverAddr;
int Port = ;
int Ret; if (argc <= )
{
cout<<"USAGE: udpclient <Server IP address>.\n";
return -;
} // Initialize Winsock version 2.2 if ((Ret = WSAStartup(MAKEWORD(,), &wsaData)) != )
{
cout<<"WSAStartup failed with error "<<Ret<<endl;
return -;
} // Create a new socket to make a client connection. SendingSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//Note the difference with TCP
if (INVALID_SOCKET == SendingSocket)
{
cout << "socket failed with error " << WSAGetLastError()<<endl;
WSACleanup();
return -;
} ReceiverAddr.sin_family = AF_INET;
ReceiverAddr.sin_port = htons(Port);
ReceiverAddr.sin_addr.s_addr = inet_addr(argv[]); // Make a connection to the server with socket s. cout<< "We are trying to connect to " << inet_ntoa(ReceiverAddr.sin_addr)
<< ":" << htons(ReceiverAddr.sin_port) << "...\n"; cout << "We will now try to send a hello message.\n"; if ((Ret = sendto(SendingSocket, "Hello", , , (SOCKADDR *)&ReceiverAddr,sizeof(ReceiverAddr))) == SOCKET_ERROR)
{
cout << "Sendto failed with error " << WSAGetLastError()<<endl;
closesocket(SendingSocket);
WSACleanup();
return -;
} cout << "We successfully sent " << Ret << " byte(s).\n"; // When you are finished sending and receiving data on socket s,
// you should close the socket. cout << "We are closing the connection.\n"; closesocket(SendingSocket); // When your application is finished handling the connection, call
// WSACleanup. WSACleanup();
return ;
}

Sender Code

Winsock网络编程笔记(3)----基于UDP的server和client的更多相关文章

  1. Linux 系统编程 学习:07-基于socket的网络编程2:基于 UDP 的通信

    Linux 系统编程 学习:07-基于socket的网络编程2:基于 UDP 的通信 背景 上一讲我们介绍了网络编程的一些概念.socket的网络编程的有关概念 这一讲我们来看UDP 通信. 知识 U ...

  2. Winsock网络编程笔记(1)----入门

    今天第一次接触winsock网络编程,看的资料是Windows网络编程第二版.通过博客记住自己的看书笔记.. 在这里贴出第一个程序,虽然程序什么都没做,但以此作为入门,熟悉其网络编程风格.. #inc ...

  3. Winsock网络编程笔记(2)----基于TCP的server和client

    今天抽空看了一些简单的东西,主要是对服务器server和客户端client的简单实现. 面向连接的server和client,其工作流程如下图所示: 服务器和客户端将按照这个流程就行开发..(个人觉得 ...

  4. Winsock网络编程笔记(4)----基本的理论知识

    前面的笔记记录了Winsock的入门编程,领略了Winsock编程的乐趣..但这并不能算是掌握了Winsock,加深理论知识的理解才会让后续学习更加得心应手..因此,这篇笔记将记录一些有关Winsoc ...

  5. 网络编程[第二篇]基于udp协议的套接字编程

    udp协议下的套接字编程 一.udp是无链接的    不可靠的 而上篇的tcp协议是可靠的,会有反馈信息来确认信息交换的完成与否 基于udp协议写成的服务端与客户端,各司其职,不管对方是否接收到信息, ...

  6. 网络编程应用:基于UDP协议【实现文件下载】--练习

    要求: 基于UDP协议实现文件下载 发送方–请求–接收方发送文件–发送方接收文件 代码: 发送方: package Homework1; import java.io.File; import jav ...

  7. Java基础知识强化之网络编程笔记04:UDP之发送端的数据来自于键盘录入案例

    1. 数据来自于键盘录入 键盘录入数据要自己控制录入结束. 2. 代码实现: (1)发送端: package com.himi.updDemo1; import java.io.IOException ...

  8. Java基础知识强化之网络编程笔记03:UDP之UDP协议发送数据 和 接收数据

    1. UDP协议发送数据 和 接收数据 UDP协议发送数据: • 创建发送端的Socket对象 • 创建数据,并把数据打包 • 调用Socket对象的发送方法,发送数据包 • 释放资源  UDP协议接 ...

  9. 网络编程应用:基于UDP协议【实现聊天程序】--练习

    要求: 使用UDP协议实现一个聊天程序 代码: 发送端: package UDP聊天程序; import java.io.IOException; import java.net.DatagramPa ...

随机推荐

  1. PHP获取文件的绝对路径

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 ===========PH ...

  2. JAVA实现上传文件到服务器、删除服务器文件

    使用的jar包: <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</art ...

  3. iOS连续dismiss几个ViewController的方法

    原文链接:http://blog.csdn.net/longshihua/article/details/51282388 presentViewController是经常会用到的展现ViewCont ...

  4. 学习ExtJS的grid布局

    这是之前学习ExtJS布局的时候我导师让我重点熟悉的内容.之后会发一个最近写的结合MVC项目的grid布局的案例. 上一篇关于ExtJS的学习资料什么的都已经更在上一篇了,这里只是对一些代码的记录. ...

  5. 51 nod 1624 取余最长路 思路:前缀和 + STL(set)二分查找

    题目: 写这题花了我一上午时间. 下面是本人(zhangjiuding)的思考过程: 首先想到的是三行,每一行一定要走到. 大概是这样一张图 每一行长度最少为1.即第一行(i -1) >= 1, ...

  6. 关于 String 自我理解

    String 的一些认识: String对象是不可变,所以使用 final 修饰 字符串拼接,合理利用 StringBuilder(线程非安全),StringBuffer 线程安全 常用方法就不详细介 ...

  7. jdk8与jdk9的共存

    以前安装JDK,需要手动配置环境变量.JDK8多了自动配置环境变量,所以可以不用手动配置. 如果我已经装了JDK8,还想再装一个JDK9,安装完,自动配置的环境变量会指向JDK9版本. 解决方法 删除 ...

  8. EsRejectedExecutionException排错与线程池类型

    1.EsRejectedExecutionException异常示例 java.util.concurrent.ExecutionException: RemoteTransportException ...

  9. 关闭eclipse自动弹出console的功能

    当启动项目后,console有值时就会弹出,挺烦人的,可以如下修改

  10. 【学习】js学习笔记:数组(一)

    1.创建数组并赋值 //对象方式 var arr=new Array(1,2,3,4); //隐形声明方式 var arr2=[5,6,7,8]; 2.数组可以存储任何类型的数据 3.访问数组,是用下 ...