套接字
网络套接字
原始套接字
unix套接字
windows下SOCKET 为整数。
协议家族 套接字种类 协议
udpServer.cc
#pragma warning(disable:4996)
#include<iostream>
#include<string>
#include<cstdlib>
#include<WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
uint16_t serverport = 8080;
string serverip = "192.168.88.130";
int main()
{
WSAData wsd; //初始化信息
//启动Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {/*进行WinSocket的初始化,
windows 初始化socket网络库,申请2,2的版本,windows socket编程必须先初始化。*/
cout << "WSAStartup Error = " << WSAGetLastError() << endl;
return 0;
}
else {
cout << "WSAStartup Success" << endl;
}
//创建套接字
SOCKET csock = socket(AF_INET, SOCK_DGRAM, 0);
if (csock == SOCKET_ERROR)
{
cout << "socket Error = " << WSAGetLastError() << endl;
return 1;
}
else {
cout << "socket Success" << endl;
}
//udp客户端不需要显示的绑定,但可以指定
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(serverport);
//将字符串转为点分十进制的ip
server.sin_addr.s_addr = inet_addr(serverip.c_str());
#define NUM 1024
char inbuffer[NUM];
//将信息发出
string line;
while (true)
{
cout << "Please Enter# ";
getline(cin, line);
int n = sendto(csock, line.c_str(), line.size(), 0, (struct sockaddr*)&server, sizeof(server));
if (n < 0)
{
cerr << "sendto error!!!" << endl;
break;
}
struct sockaddr_in peer;
int peerlen = sizeof(peer);
//收取数据
inbuffer[0] = 0;
n = recvfrom(csock, inbuffer, sizeof(inbuffer)-1,0, (struct sockaddr*)&peer, &peerlen);
}
closesocket(csock);
WSACleanup();
return 0;
}
【干货】Windows平台基于udp的socket网络编程开发_windows udp socket-CSDN博客
Linux和Windows跨平台通信