Unigine.Socket Class
Inherits from: | Stream |
This class provides basic functionality for network interaction using stream sockets.
Usage Example
In this example we create UDP sockets: server and five clients.
- The server sends broadcast packets containing the ID of the receiving client.
- Each client processes only the messages, that were addressed to it.
- In the world's update() method the server sends messages addressed to clients 2 and 5.
In the AppWorldLogic.cs we do the following:
- First, we describe our client and server and declare server and array of clients.
- In the AppWorldLogic.init() method we initialize our clients.
- In the AppWorldLogic.update() we check which keys were pressed and send messages to corresponding clients:
- Client 2 - on ENTER key
- Client 5 - on WASD keys
//AppWorldLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace UnigineApp
{
static class Constants
{
// UDP port to be used
public const int UDP_PORT = 8889;
// UDP receive buffer size
public const int RECV_SIZE = 7;
// UDP send buffer size
public const int SEND_SIZE = 7;
}
/// Class representing the Server Socket
class ServerSocket
{
Socket socket;
/// Server constructor
public ServerSocket()
{
// creating a UDP socket
socket = new Socket(Socket.SOCKET_DGRAM);
// opening a socket on the specified port with a specified broadcast address
socket.Open("127.255.255.255", Constants.UDP_PORT);
// setting the size of the sending buffer
socket.Send(Constants.SEND_SIZE);
// setting the socket as a broadcasting one
socket.Broadcast();
// setting the socket as a non-blocking one
socket.Nonblock();
}
/// Server destructor
~ServerSocket()
{
// closing the socket
socket.Close();
}
/// method sending a message to a certain client
public void send_message(short client_num, string message)
{
// preparing a message to be received by a client with a given client_id
Blob blob = new Blob();
blob.Clear();
blob.WriteShort(client_num);
blob.Write(Marshal.StringToHGlobalUni(message), (uint)message.Length);
// getting message size
uint size = blob.GetSize();
// setting current position to start
blob.SeekSet(0);
// sending the message
socket.WriteStream(blob, size);
blob.Clear();
}
};
/// Class representing the Client Socket
class ClientSocket
{
Socket socket;
int id = 0;
/// Client constructor
public ClientSocket()
{
// creating a UDP socket
socket = new Socket(Socket.SOCKET_DGRAM);
// opening a socket on the specified port
socket.Open(Constants.UDP_PORT);
// setting the size of the receiving buffer
socket.Recv(Constants.RECV_SIZE);
// binding the socket to an address figured out from the host used for socket initialization
socket.Bind();
// setting the socket as a non-blocking one
socket.Nonblock();
}
/// Client destructor
~ClientSocket()
{
// closing the socket
socket.Close();
}
public void setID(int num)
{
// setting client's ID
id = num;
}
/// method checking for received packes from the server
public int update()
{
// preparing a blob to read the message into
Blob temp_blob = new Blob();
temp_blob.Clear();
// reading data from the socket
socket.ReadStream(temp_blob, Constants.RECV_SIZE);
if (temp_blob.GetSize() > 0)
{
// setting current position to start
temp_blob.SeekSet(0);
// getting client's ID
short num_client = temp_blob.ReadShort();
// checking if the received message is addressed to this particular client and processing it
if (num_client == id)
Log.Message("\nClient[{0}] - OPERATION_CODE: {1}", id, temp_blob.ReadLine());
}
return 1;
}
};
class AppWorldLogic : WorldLogic
{
//declaring server and client sockets
ServerSocket server_socket;
ClientSocket[] clients = new ClientSocket[5];
// World logic, it takes effect only when the world is loaded.
// These methods are called right after corresponding world script's (UnigineScript) methods.
public AppWorldLogic()
{
}
public override bool Init()
{
server_socket = new ServerSocket();
// Write here code to be called on world initialization: initialize resources for your world scene during the world start.
for (int i = 0; i < 5; i++)
{
clients[i] = new ClientSocket();
clients[i].setID(i + 1);
}
return true;
}
// start of the main loop
public override bool Update()
{
// Write here code to be called before updating each render frame: specify all graphics-related functions you want to be called every frame while your application executes.
Controls controls = Game.Player.Controls;
// sending messages on keys pressed to clients 2 and 5
if (controls.ClearState(Controls.STATE_USE) == 1)
server_socket.send_message(2, "S");
else if (controls.ClearState(Controls.STATE_FORWARD) == 1)
server_socket.send_message(5, "F");
else if (controls.ClearState(Controls.STATE_BACKWARD) == 1)
server_socket.send_message(5, "B");
else if (controls.ClearState(Controls.STATE_MOVE_LEFT) == 1)
server_socket.send_message(5, "L");
else if (controls.ClearState(Controls.STATE_MOVE_RIGHT) == 1)
server_socket.send_message(5, "R");
// updating clients
for (int i = 0; i < 5; i++)
clients[i].update();
return true;
}
/* ... */
}
}
See Also#
A set of UnigineScript API samples located in the <UnigineSDK>/data/samples/systems/ folder:
- socket_00
- socket_01
- socket_02
- socket_03
- socket_04
Socket Class
Members
Socket ( int type ) #
Creates a socket and opens it on a given port. When the socket receives data, packets from all network interfaces will be received. When the socket sends data, the default IP address will be used.Arguments
- int type - Port, on which the socket will be opened.
Socket ( int type, int port ) #
Creates a socket for TCP or UDP connections and opens it on a given port. When the socket receives data, packets from all network interfaces will be received. When the socket sends data, the default IP address will be used.Arguments
- int type - Socket for TCP (SOCKET_STREAM variable) or UDP (SOCKET_DGRAM) connections.
- int port - Port, on which the socket will be opened.
Socket ( int type, string host, int port ) #
Creates a socket for TCP or UDP connections and opens it on a given host and a given port. The host specifies the address, from and to which data will be sent.Arguments
- int type - Socket for TCP (SOCKET_STREAM variable) or UDP (SOCKET_DGRAM) connections.
- string host - Host, on which the socket will be opened.
- int port - Port, on which the socket will be opened.
int GetFD ( ) #
Returns the socket file descriptor.Return value
Socket file descriptor.string GetHost ( ) #
Returns the host name on which the socket is opened.Return value
Host name.int GetPort ( ) #
Returns the port number on which the socket is opened.Return value
Port number.int Accept ( Socket socket ) #
Accepts a connection on the socket.Arguments
- Socket socket - Socket that is bound to an address and listens to connections.
Return value
1 if the connection is accepted; otherwise, 0.int Bind ( ) #
Binds the socket to an address figured out from the host used for socket initialization.Return value
1 if the address is bound; otherwise, 0.int Block ( ) #
Sets up a blocking socket.Return value
1 if the socket is opened; otherwise, 0.int Broadcast ( ) #
Sets up a broadcast socket. To create a broadcast socket, you need to create it with a broadcast host address first and then use this function.Return value
1 if the socket is set up successfully ; otherwise, 0 is returned.int Close ( ) #
Closes the socket.int Connect ( ) #
Initiates a connection on the socket.Return value
1 if the connection is initialized; otherwise, 0.int Listen ( int num ) #
Makes the socket listen to connections.Arguments
- int num - Maximum number of pending connections.
Return value
1 if the socket has started listening; otherwise, 0.int ListenMulticastGroup ( ) #
Joins the socket to a multicast group. Available for UDP sockets only.The socket class doesn't allow creating a multicast server.
const int PORT = 8888;
Socket socket = new Socket(Socket.SOCKET_DGRAM, PORT);
socket.listenMulticastGroup();
Return value
1 if the sockect has been joined successfully; otherwise, 0.int Nodelay ( ) #
Enables Nagle's algorithm.Return value
1 if the algorithm has been enabled successfully; otherwise, 0.int Nonblock ( ) #
Makes the socket a non-blocking one.Return value
1 if the has become non-blocking; otherwise, 0.int Open ( int port ) #
Opens the socket on a given port. When the socket receives data, packets from all network interfaces will be received. When the socket sends data, the default IP address will be used.Arguments
- int port - Port number, on which the socket will be opened.
Return value
1 if the socket is opened successfully; otherwise, 0.int Open ( string host, int port ) #
Opens the socket on a given port. When the socket receives data, packets from all network interfaces will be received. When the socket sends data, the default IP address will be used.Arguments
- string host - Host name, on which the socket will be opened.
- int port - Port number, on which the socket will be opened.
Return value
1 if the socket is opened successfully; otherwise, 0.int Recv ( int size ) #
Resizes an internal receiving buffer for a socket.Arguments
- int size - Receive buffer size in bytes.
Return value
1 if the buffer is resized successfully; otherwise, 0.int Send ( int size ) #
Resizes an internal sending buffer for a socket.Arguments
- int size - Send buffer size in bytes.
Return value
1 if the buffer is resized successfully; otherwise, 0.int IsReadyToRead ( int timeout_usec = 0 ) #
Returns a value indicating whether the socked is ready for reading data, waiting if necessary, to perform synchronous I/O.Arguments
- int timeout_usec - The maximum time for to wait for the socket's response, in microseconds. By default, the timeout is 0
Return value
1 if the socket is ready for reading data; otherwise, 0.int IsReadyToWrite ( int timeout_usec = 0 ) #
Returns a value indicating whether the socked is ready for writing data, waiting if necessary, to perform synchronous I/O.Arguments
- int timeout_usec - The maximum time for to wait for the socket's response, in microseconds. By default, the timeout is 0
Return value
1 if the socket is ready for writing data; otherwise, 0.Last update:
2021-12-13
Help improve this article
Was this article helpful?
(or select a word/phrase and press Ctrl+Enter)