服务端
如果对socket()、bind()函数不理解,请看另一篇博文:
- windows上用c/c++实现socket tcp编程
https://blog.csdn.net/u013749051/article/details/102790585
#include <iostream>
#include <thread>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
using namespace std;
int main() {
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
int server = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = 0;
addr.sin_port = htons(8080);
int bindRet = bind(server, (sockaddr*)& addr, sizeof(addr));
if (bindRet == -1) {
cout << "绑定端口失败,或许端口已经被占用" << errno << endl;
exit(0);
}
cout << "udp服务启动,正确8080端口监听" << endl;
while (true) {
char buf[100];
int len = 666;
/*
int fd : 套接字描述符
char* buf : 缓冲区
int bufSize : 缓冲区大小
int flags : 给0就可以了
sockaddr* addr : 用来保存接收到的地址
int* addrLen : 用来保存前一个参数的长度
成功返回实际接收的字节数
失败返回-1
*/
int recvRet = recvfrom(server, buf, sizeof(buf), 0, (sockaddr*)& addr, &len);
if (recvRet == -1) {
cout << "接收失败:" << errno << endl;
break;
}
cout << "收到:" << buf << endl;
strcpy(buf, "你好客户端");
/*
int fd : 套接字描述符
const char* msg : 消息缓冲区---即要发送的消息
int msgSize : 消息缓冲区大小
int flags : 给0就可以了
sockaddr* addr : 用来指定要发送的目标ip和端口号
int addrLen : 用来指定前一个参数的长度
成功返回已经发送的字节数
失败返回-1
*/
int sendRet = sendto(server, buf, sizeof(buf), 0, (sockaddr*)& addr, sizeof(addr));
if (sendRet == -1) {
cout << "发送失败" << errno << endl;
break;
}
}
cout << "服务运行结束:" << errno << endl;
}
客户端
#include <iostream>
#include <thread>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
using namespace std;
int main() {
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
int client = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(8080);
char buf[100] = "你好服务器";
int sendRet = sendto(client, buf, sizeof(buf), 0, (sockaddr*)& addr, sizeof(addr));
if (sendRet == -1) {
cout << "发送失败:" << errno << endl;
exit(0);
}
int len = 666;
int recvRet = recvfrom(client, buf, sizeof(buf), 0, (sockaddr*)& addr, &len);
if (recvRet == -1) {
cout << "接收失败" << errno << endl;
exit(0);
}
cout << "收到:" << buf << endl;
}