More socket API changes

This commit is contained in:
Jak Barnes 2019-02-23 00:10:18 +00:00
parent 4c9057cec2
commit 97d01fe36d
7 changed files with 867 additions and 699 deletions

View File

@ -1,62 +1,72 @@
/*******************************************************************************************
* #include <iostream>
* raylib [core] example - Basic window #include "raylib.h"
* #include <vector>
* Welcome to raylib! #include <time.h>
*
* To test examples, just press F6 and execute raylib_compile_execute script using namespace std;
* Note that compiled executable is placed in the same folder as .c file
* typedef struct room
* You can find all basic examples on C:\raylib\raylib\examples folder or {
* raylib official webpage: www.raylib.com int x = 0;
* int y = 0;
* Enjoy using raylib. :) int width = 10;
* int height = 10;
* This example has been created using raylib 1.0 (www.raylib.com) };
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5) room Temp_Rect_Creat()
* {
********************************************************************************************/ room in_creation;
#include "raylib.h" in_creation.x = int(rand() % 700);
in_creation.y = int(rand() % 400);
int main(int argc, char* argv[])
{ in_creation.width = int(rand() % 50);
// Initialization if (in_creation.width < 10) in_creation.width = 10;
//-------------------------------------------------------------------------------------- in_creation.height = int(rand() % 70);
int screenWidth = 800; if (in_creation.height < 10) in_creation.height = 10;
int screenHeight = 450;
return in_creation;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window"); }
SetTargetFPS(60); int main()
//-------------------------------------------------------------------------------------- {
srand(time(NULL));
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key int screenWidth = 800;
{ int screenHeight = 450;
// Update
//---------------------------------------------------------------------------------- vector<room> rooms;
// TODO: Update your variables here InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input");
//----------------------------------------------------------------------------------
Vector2 ballPosition = { (float)screenWidth / 2, (float)screenHeight / 2 };
// Draw
//---------------------------------------------------------------------------------- SetTargetFPS(60);
BeginDrawing();
int i = 0;
ClearBackground(RAYWHITE); while (i < 20)
{
DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); room temp = Temp_Rect_Creat();
rooms.push_back(temp);
EndDrawing(); i++;
//---------------------------------------------------------------------------------- }
}
while (!WindowShouldClose())
// De-Initialization {
//-------------------------------------------------------------------------------------- BeginDrawing();
CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- ClearBackground(RAYWHITE);
return 0; for (int i = 0; i < rooms.size(); i++)
{
DrawRectangle(rooms[i].x, rooms[i].y, rooms[i].width, rooms[i].height, BLACK);
}
EndDrawing();
}
CloseWindow();
return 0;
} }

View File

@ -32,7 +32,7 @@ int main()
SetTargetFPS(60); SetTargetFPS(60);
// Networking // Networking
InitNetwork(); InitNetwork();
// Main game loop // Main game loop
while (!WindowShouldClose()) while (!WindowShouldClose())

View File

@ -22,6 +22,9 @@
#include "raylib.h" #include "raylib.h"
#define MYPORT "4950"
#define MAXBUFLEN 100
int main() int main()
{ {
// Setup // Setup
@ -32,7 +35,7 @@ int main()
SetTargetFPS(60); SetTargetFPS(60);
// Networking // Networking
InitNetwork(); InitNetwork();
// Main game loop // Main game loop
while (!WindowShouldClose()) while (!WindowShouldClose())
@ -47,7 +50,7 @@ int main()
EndDrawing(); EndDrawing();
} }
// Cleanup // Cleanup
CloseWindow(); CloseWindow();
return 0; return 0;
} }

View File

@ -23,10 +23,9 @@
#include "raylib.h" #include "raylib.h"
int main() int main()
{ {
// Setup // Setup
int screenWidth = 800; int screenWidth = 800;
int screenHeight = 450; int screenHeight = 450;
InitWindow( InitWindow(
screenWidth, screenHeight, "raylib [network] example - ping pong"); screenWidth, screenHeight, "raylib [network] example - ping pong");
@ -37,29 +36,45 @@ int main()
// Networking // Networking
InitNetwork(); InitNetwork();
// Server socket and address // Create the server
AddressInformation serveraddr; SocketConfig server_cfg = {
Socket server; .host = "127.0.0.1",
server.blocking = false; .port = 8080,
ResolveHost(&serveraddr, "localhost", "3490", SOCKET_TCP); .server = true,
.nonblocking = true,
};
CreateSocket(&server, serveraddr); SocketResult server_res;
BindSocket(server, serveraddr); memset(&server_res, 0, sizeof(SocketResult));
ListenSocket(server); {
bool ok = SocketOpen(&server_cfg, &server_res);
if (!ok) { return false; }
}
// Client socket and address // Create the client
AddressInformation clientaddr; SocketConfig client_cfg = {
Socket client; .host = "127.0.0.1",
client.blocking = false; .port = 8080,
ResolveHost(&clientaddr, "localhost", "3490", SOCKET_TCP); };
CreateSocket(&client, clientaddr);
ConnectSocket(client, clientaddr);
Socket connection; // The socket connection between server->client SocketResult client_res;
float elapsed = 0.0f, delay = 1.0f; // ms memset(&client_res, 0, sizeof(SocketResult));
bool ping = false, pong = false; {
char recvBuffer[512]; bool ok = SocketOpen(&client_cfg, &client_res);
bool connected = false; if (!ok)
{
printf("failed to open: status %d, errno %d\n",
client_res.status, client_res.saved_errno);
return false;
}
}
SocketResult connection;
memset(&connection, 0, sizeof(SocketResult));
float elapsed = 0.0f, delay = 1.0f; // ms
bool ping = false, pong = false;
char recvBuffer[512];
bool connected = false;
memset(&recvBuffer, 0, 8); memset(&recvBuffer, 0, 8);
// Main game loop // Main game loop
@ -74,15 +89,17 @@ int main()
// A valid connection will != -1 // A valid connection will != -1
if (!connected) if (!connected)
{ {
AcceptSocket(server, &connection); if (SocketAccept(server_res.socket.handle, &connection))
ping = true; {
connected = true; ping = true;
connected = true;
}
} }
// Connected // Connected
if (connected) if (connected)
{ {
int bytesRecv = ReceiveTCP(connection.handle, recvBuffer, 5); int bytesRecv = SocketReceive(&connection.socket, recvBuffer, 5);
if (bytesRecv > 0) if (bytesRecv > 0)
{ {
if (strcmp(recvBuffer, "Ping!") == 0) if (strcmp(recvBuffer, "Ping!") == 0)
@ -103,12 +120,12 @@ int main()
if (ping) if (ping)
{ {
ping = false; ping = false;
SendTCP(client.handle, "Ping!", 5); SocketSend(&client_res.socket, "Ping!", 5);
} }
else if (pong) else if (pong)
{ {
pong = false; pong = false;
SendTCP(client.handle, "Pong!", 5); SocketSend(&client_res.socket, "Pong!", 5);
} }
elapsed = 0.0f; elapsed = 0.0f;
} }

View File

@ -1,62 +1,67 @@
/*******************************************************************************************
*
* raylib [core] example - Basic window
*
* Welcome to raylib!
*
* To test examples, just press F6 and execute raylib_compile_execute script
* Note that compiled executable is placed in the same folder as .c file
*
* You can find all basic examples on C:\raylib\raylib\examples folder or
* raylib official webpage: www.raylib.com
*
* Enjoy using raylib. :)
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h" #include "raylib.h"
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
typedef struct room {
int x = 0;
int y = 0;
int width = 10;
int height = 10;
};
room Temp_Rect_Creat() {
room in_creation;
in_creation.x = int (rand() % 700);
in_creation.y = int (rand() % 400);
in_creation.width = int(rand() % 50);
if (in_creation.width < 10) in_creation.width = 10;
in_creation.height = int(rand() % 70);
if (in_creation.height < 10) in_creation.height = 10;
return in_creation;
}
int main() int main()
{ {
// Initialization srand(time(NULL));
//--------------------------------------------------------------------------------------
int screenWidth = 800; int screenWidth = 800;
int screenHeight = 450; int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window"); vector<room> rooms;
InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input");
Vector2 ballPosition = { (float)screenWidth / 2, (float)screenHeight / 2 };
SetTargetFPS(60); SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop int i = 0;
while (!WindowShouldClose()) // Detect window close button or ESC key while (i < 20) {
{ room temp = Temp_Rect_Creat();
// Update rooms.push_back(temp);
//---------------------------------------------------------------------------------- i++;
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
} }
// De-Initialization while (!WindowShouldClose())
//-------------------------------------------------------------------------------------- {
CloseWindow(); // Close window and OpenGL context BeginDrawing();
//--------------------------------------------------------------------------------------
ClearBackground(RAYWHITE);
for (int i = 0; i < rooms.size(); i++) {
DrawRectangle(rooms[i].x, rooms[i].y, rooms[i].width, rooms[i].height, BLACK);
}
EndDrawing();
}
CloseWindow();
return 0; return 0;
} }

View File

@ -100,10 +100,12 @@
// Network limits // Network limits
#define MAX_SOCKET_SET_SIZE 32 #define MAX_SOCKET_SET_SIZE 32
#define MAX_SOCKET_QUEUE_SIZE 16 #define MAX_SOCKET_QUEUE_SIZE 16
#define MAX_HOST_NAME_SIZE NI_MAXHOST #define MAX_HOST_NAME_SIZE 1025
#define MAX_SERV_NAME_SIZE NI_MAXSERV #define MAX_SERV_NAME_SIZE 32
#define MAX_IPV4_NAME_SIZE INET6_ADDRSTRLEN #define MAX_IPV4_NAME_SIZE 22
#define MAX_IPV6_NAME_SIZE INET_ADDRSTRLEN #define MAX_IPV6_NAME_SIZE 65
#define MAX_SOCK_OPTS 4
// NOTE: MSC C++ compiler does not support compound literals (C99 feature) // NOTE: MSC C++ compiler does not support compound literals (C99 feature)
// Plain structures in C++ (without constructors) can be initialized from { } initializers. // Plain structures in C++ (without constructors) can be initialized from { } initializers.
@ -427,107 +429,119 @@ typedef struct VrStereoConfig {
Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices
int eyeViewportRight[4]; // VR stereo rendering right eye viewport [x, y, w, h] int eyeViewportRight[4]; // VR stereo rendering right eye viewport [x, y, w, h]
int eyeViewportLeft[4]; // VR stereo rendering left eye viewport [x, y, w, h] int eyeViewportLeft[4]; // VR stereo rendering left eye viewport [x, y, w, h]
} VrStereoConfig; } VrStereoConfig;
typedef struct IPAddress typedef struct IPAddress
{ {
int family; unsigned char* host; /* 32-bit IPv4 host address */
union { unsigned char* port; /* 16-bit protocol port */
struct } IPAddress;
{
unsigned int host; /* 32-bit IPv4 host address */
unsigned short port; /* 16-bit protocol port */
} ip4;
struct
{
unsigned char host[16]; /* 128-bit IPv6 host address */
} ip6;
} data;
} IPAddress;
typedef struct IPv4address
{
unsigned int host; /* 32-bit IPv4 host address */
unsigned short port; /* 16-bit protocol port */
} IPv4address;
typedef struct IPv6address
{
unsigned char bytes[16]; /* 128-bit IPv6 host address */
} IPv6address;
typedef struct AddressInformation typedef struct AddressInformation
{ {
int flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST int flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
int family; // PF_xxx int family; // PF_xxx
int socktype; // SOCK_xxx int socktype; // SOCK_xxx
int protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6 int protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6
unsigned int addrlen; // Length of ai_addr unsigned int addrlen; // Length of ai_addr
char * canonname; // Canonical name for nodename char * canonname; // Canonical name for nodename
struct SocketAddress *sockaddr; // Binary address struct SocketAddress *sockaddr; // Binary address
struct AddressInformation *next; // Next structure in linked list struct AddressInformation *next; // Next structure in linked list
} AddressInformation; } AddressInformation;
typedef struct SocketAddress typedef struct SocketAddress
{ {
unsigned short family; // Address family. unsigned short family; // Address family.
char data[14]; // Up to 14 bytes of direct address. char data[14]; // Up to 14 bytes of direct address.
} SocketAddress; } SocketAddress;
/* An option ID, value, sizeof(value) tuple for setsockopt(2). */
typedef struct SocketOpt {
int option_id;
void *value;
int value_len;
} SocketOpt;
// Socket
typedef struct Socket typedef struct Socket
{ {
int ready; int ready;
SocketHandle handle; SocketHandle handle;
IPv4address address; IPAddress remoteAddress;
bool blocking; IPAddress localAddress;
// int ready; int sflag;
// SocketHandle handle;
// IPAddress address;
// bool blocking;
} Socket; } Socket;
/* Configuration for a socket. Not all of these fields need to
* be set, and ones omitted from a C99-style "designated initializer"
* struct literal will be zeroed out and replaced with defaults. */
typedef struct SocketConfig {
/* Hostname and port, for TCP or UDP sockets. */
char *host;
int port;
//typedef struct UDPSocket /* Path, for Unix domain socket. */
//{ char *path;
// int ready;
// SocketHandle handle;
// IPAddress address;
// bool blocking;
//} UDPSocket;
//
//typedef struct UDPPacket
//{
// int channel; /* The src/dst channel of the packet */
// char * data; /* The packet data */
// int len; /* The length of the packet data */
// int maxlen; /* The size of the data buffer */
// int status; /* packet status after sending */
// IPAddress address; /* The source/dest address of an incoming/outgoing packet */
//} UDPPacket;
//
//typedef struct TCPSocket
//{
// int ready;
// SocketHandle channel;
// IPAddress remoteAddress;
// IPAddress localAddress;
// bool isServer;
// bool blocking;
//} TCPSocket;
//
//typedef struct TCPPacket
//{
// const void *data; /* The packet data */
// int len; /* The length of the packet data */
// int maxlen; /* The size of the data buffer */
//} TCPPacket;
typedef struct SocketSet /* IPv4 or IPv6 address; if neither is specified, let OS decide.
{ * These fields should be used in place of 'host' above. */
Socket *sockets[MAX_SOCKET_SET_SIZE]; char *IPv4;
} SocketSet; char *IPv6;
bool server; /* Listen for incoming clients? */
bool datagram; /* UDP or datagram Unix domain? */
bool nonblocking; /* non-blocking operation? */
int backlog_size; /* set a custom backlog size */
SocketOpt sockopts[MAX_SOCK_OPTS];
} SocketConfig;
enum SocketStatus {
/* Socket created. */
SOCKET_OK = 0,
/* Failures from socket API functions; most also save errno. */
SOCKET_ERROR_GETADDRINFO = -1,
SOCKET_ERROR_SOCKET = -2,
SOCKET_ERROR_BIND = -3,
SOCKET_ERROR_LISTEN = -4,
SOCKET_ERROR_CONNECT = -5,
SOCKET_ERROR_FCNTL = -6,
SOCKET_ERROR_ACCEPT = -7,
SOCKET_ERROR_SEND = -8,
/* Failure from snprintf: name too long. */
SOCKET_ERROR_SNPRINTF = -100,
/* Invalid combination of options in configuration. */
SOCKET_ERROR_CONFIGURATION = -200,
/* Error in setsockopt(2). */
SOCKET_ERROR_SETSOCKOPT = -300,
/* Other unknown error. */
SOCKET_ERROR_UNKNOWN = -400,
};
/* Result from calling open with a given config. */
typedef struct SocketResult {
/* Result code and errno value from failure (if any). */
enum SocketStatus status;
/* File descriptor, set if status is SOCKET99_OK (success). */
Socket socket;
/* Address information populated from getaddrinfo() */
AddressInformation addrinfo;
/* Error code from socket(2), bind(2), etc. */
int saved_errno;
/* Error code from getaddrinfo, only set if status is
* SOCKET99_ERROR_GETADDRINFO. See: gai_strerror(3). */
int getaddrinfo_error;
} SocketResult;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Enumerators Definition // Enumerators Definition
@ -537,13 +551,7 @@ typedef enum
{ {
SOCKET_TCP = 1, // SOCK_STREAM SOCKET_TCP = 1, // SOCK_STREAM
SOCKET_UDP = 2 // SOCK_DGRAM SOCKET_UDP = 2 // SOCK_DGRAM
} SocketType; } SocketType;
typedef enum
{
FAMILY_IPv4 = 1,
FAMILY_IPv6 = 2
} AddressFamily;
// System config flags // System config flags
// NOTE: Used for bit masks // NOTE: Used for bit masks
@ -1498,24 +1506,35 @@ RLAPI void StopAudioStream(AudioStream stream); // Stop au
RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level)
RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level)
// Network functions //------------------------------------------------------------------------------------
RLAPI bool InitNetwork(void); // Network (Module: network)
RLAPI void CloseNetwork(void); //------------------------------------------------------------------------------------
RLAPI void ResolveHost(AddressInformation *outaddr, const char *address, const char *port, SocketType socketType);
RLAPI char *ResolveIP(const char *host, const char *port);
RLAPI bool IsIPv4Address(const char *host);
RLAPI bool IsIPv6Address(const char *host);
RLAPI int GetIPFamily(const char *host);
RLAPI void GetLocalAddresses();
RLAPI bool CreateSocket(Socket *socket, AddressInformation outaddr);
RLAPI bool BindSocket(Socket socket, const AddressInformation addr);
RLAPI bool ConnectSocket(Socket socket, const AddressInformation addr);
RLAPI bool ListenSocket(Socket socket);
RLAPI void CloseSocket(Socket *socket);
RLAPI void AcceptSocket(Socket listenSock, Socket *newSock);
RLAPI char *SocketAddressToString(SocketAddress *sockaddr, char buffer[]);
RLAPI void PrintSocket(SocketAddress *addr, const int family, const int socktype, const int protocol);
RLAPI bool InitNetwork(void);
RLAPI void CloseNetwork(void);
// Resolution
RLAPI void ResolveHost(AddressInformation *outaddr, const char *address, const char *port, SocketType socketType);
RLAPI char *ResolveIP(const char *host, const char *port);
// IP
RLAPI void GetLocalAddresses();
// Socket API
RLAPI bool SocketOpen(SocketConfig *cfg, SocketResult *res);
RLAPI void SocketClose(SocketHandle socket);
RLAPI bool SocketAccept(SocketHandle listener, SocketResult* res);
RLAPI int SocketSend(Socket* socket, const void *datap, int len);
RLAPI int SocketReceive(Socket* socket, void *data, int maxlen);
RLAPI int SocketGetError(char *buf, int buf_size, SocketResult *res);
RLAPI void SocketPrintError(SocketResult *res);
RLAPI void SocketSetHints(SocketConfig *cfg, AddressInformation *hints);
// Print methods
RLAPI char *SocketAddressToString(SocketAddress *sockaddr, char buffer[]);
RLAPI void PrintSocket(SocketAddress *addr, const int family, const int socktype, const int protocol);
// Network conversion methods
RLAPI unsigned int PackData(unsigned char *buf, char *format, ...); RLAPI unsigned int PackData(unsigned char *buf, char *format, ...);
RLAPI void UnpackData(unsigned char *buf, char *format, ...); RLAPI void UnpackData(unsigned char *buf, char *format, ...);
RLAPI unsigned short HostToNetworkShort(unsigned short value); // 2 bytes - 0 to 65,535 RLAPI unsigned short HostToNetworkShort(unsigned short value); // 2 bytes - 0 to 65,535
@ -1528,11 +1547,6 @@ RLAPI unsigned long NetworkToHostLong(unsigned long value); // 4 byte - 0 to 4,2
RLAPI float NetworkToHostFloat(unsigned int value); // 4 byte - 1.2E-38 to 3.4E+38 RLAPI float NetworkToHostFloat(unsigned int value); // 4 byte - 1.2E-38 to 3.4E+38
RLAPI double NetworkToHostDouble(unsigned long long value); // 8 byte - 2.3E-308 to 1.7E+308 RLAPI double NetworkToHostDouble(unsigned long long value); // 8 byte - 2.3E-308 to 1.7E+308
RLAPI unsigned long long NetworkToHostLongLong(unsigned long long value); // 8 byte - 0 to 1.8446744073709551615 × 10^19 RLAPI unsigned long long NetworkToHostLongLong(unsigned long long value); // 8 byte - 0 to 1.8446744073709551615 × 10^19
RLAPI void CreateListenServer(Socket *socket, const char *address, const int port, SocketType socketType);
RLAPI void CreateClient(Socket *socket, const char *address, const char *port, SocketType socketType);
RLAPI int Send(SocketHandle sockfd, const char *data, int len);
RLAPI int Receive(SocketHandle sockfd, const char *data, int len);
RLAPI void ResetSocket(Socket *socket);
#if defined(__cplusplus) #if defined(__cplusplus)
} }

File diff suppressed because it is too large Load Diff