With the socket functions of URScript, a program that runs on a Universal Robots cobot connects to your application and exchanges text and numbers with it. This page shows the socket server of the SDK: it listens on a port of the PC, 50001 by default, and raises an event for each message of a robot.

## How it works

The robot program opens the connection with `socket_open`, then sends and receives messages. On the PC, the SDK raises an event for each step:

| URScript of the robot                  | Event of the SDK             | Your code                                       |
| -------------------------------------- | ---------------------------- | ----------------------------------------------- |
| `socket_open("192.168.0.10", 50001)`   | `SocketClientConnection`     | Keep the client, send it a first message        |
| `socket_send_string("Hello")`          | `SocketRequest`              | Read `Message`                                  |
| `value := socket_get_var("COUNTER")`   | `SocketGetVar`               | Set `Value`, an integer, sent back to the robot |
| `socket_read_string()`                 | none                         | Send with `SocketWrite`                         |
| `socket_close()`                       | `SocketClientDisconnection`  |                                                 |

`192.168.0.10` is the address of the PC. See [TCP/IP socket communication via URScript](https://www.universal-robots.com/articles/ur/interface-communication/tcpip-socket-communication-via-urscript/) by Universal Robots.

```ruby
socket_open("192.168.0.10", 50001)
socket_send_string("Hello")
counter := socket_get_var("COUNTER")
reply := socket_read_string()
socket_close()
```

The program [socket_sample.urp](https://github.com/underautomation/UniversalRobots.NET/raw/main/UnderAutomation.UniversalRobots.Showcase.Forms/Samples/socket_sample.urp) uses these functions.

## Example

The socket server is disabled by default: set `SocketCommunication.Enable` in `ConnectParameters`.

**C# : Socket**
```csharp
using UnderAutomation.UniversalRobots;
using UnderAutomation.UniversalRobots.SocketCommunication;

class Socket
{
  static void Main(string[] args)
  {
    /**/
    var robot = new UR();

    var parameters = new ConnectParameters("192.168.0.1");

    // The socket server is disabled by default
    parameters.SocketCommunication.Enable = true;
    parameters.SocketCommunication.Port = 50001;

    robot.Connect(parameters);

    // URScript: socket_open("192.168.0.10", 50001)
    robot.SocketCommunication.SocketClientConnection += (sender, e) =>
    {
      e.Client.SocketWrite("Welcome");
    };

    // URScript: socket_send_string("Hello")
    robot.SocketCommunication.SocketRequest += (sender, e) =>
    {
      Console.WriteLine(e.Client.EndPoint.Address + " says " + e.Message);
    };

    // URScript: value := socket_get_var("COUNTER")
    robot.SocketCommunication.SocketGetVar += (sender, e) =>
    {
      if (e.Name == "COUNTER") e.Value = 12; // integer only
    };

    // URScript: socket_close()
    robot.SocketCommunication.SocketClientDisconnection += (sender, e) =>
    {
      Console.WriteLine(e.Client.EndPoint + " disconnected");
    };

    // Send a message to every connected robot
    robot.SocketCommunication.SocketWrite("Start");

    // Or to one robot
    foreach (SocketClient client in robot.SocketCommunication.ConnectedClients)
      client.SocketWrite("Hello " + client.EndPoint.Address);
    /**/
  }
}
```

**Python : Socket**
```python
from underautomation.universal_robots.ur import UR
from underautomation.universal_robots.connect_parameters import ConnectParameters
from underautomation.universal_robots.socket_communication.socket_client_connection_event_args import SocketClientConnectionEventArgs
from underautomation.universal_robots.socket_communication.socket_request_event_args import SocketRequestEventArgs
from underautomation.universal_robots.socket_communication.socket_get_var_event_args import SocketGetVarEventArgs
from underautomation.universal_robots.socket_communication.socket_client_disconnection_event_args import SocketClientDisconnectionEventArgs

##
robot = UR()

parameters = ConnectParameters("192.168.0.1")

# The socket server is disabled by default
parameters.socket_communication.enable = True
parameters.socket_communication.port = 50001

robot.connect(parameters)

# URScript: socket_open("192.168.0.10", 50001)
def on_connection(sender, e):
    SocketClientConnectionEventArgs(e._instance).client.socket_write("Welcome")

# URScript: socket_send_string("Hello")
def on_request(sender, e):
    request = SocketRequestEventArgs(e._instance)
    print(request.client.end_point, "says", request.message)

# URScript: value := socket_get_var("COUNTER")
def on_get_var(sender, e):
    request = SocketGetVarEventArgs(e._instance)
    if request.name == "COUNTER":
        request.value = 12  # integer only

# URScript: socket_close()
def on_disconnection(sender, e):
    print(SocketClientDisconnectionEventArgs(e._instance).client.end_point, "disconnected")

robot.socket_communication.socket_client_connection(on_connection)
robot.socket_communication.socket_request(on_request)
robot.socket_communication.socket_get_var(on_get_var)
robot.socket_communication.socket_client_disconnection(on_disconnection)

# Send a message to every connected robot
robot.socket_communication.socket_write("Start")

# Or to one robot
for client in robot.socket_communication.connected_clients:
    client.socket_write(f"Hello {client.end_point}")
##
```

The same server works without `UR`:

**C# : SocketDirect**
```csharp
using UnderAutomation.UniversalRobots.SocketCommunication;

class SocketDirect
{
  static void Main(string[] args)
  {
    /**/
    // A socket server, without a UR instance
    var server = new SocketCommunicationServer();

    server.SocketRequest += (sender, e) =>
    {
      Console.WriteLine(e.Client.EndPoint.Address + " says " + e.Message);
    };

    server.Start(50001);

    // ...

    server.Stop();
    /**/
  }
}
```

**Python : SocketDirect**
```python
from underautomation.universal_robots.socket_communication.socket_communication_server import SocketCommunicationServer
from underautomation.universal_robots.socket_communication.socket_request_event_args import SocketRequestEventArgs

##
# A socket server, without a UR instance
server = SocketCommunicationServer()

def on_request(sender, e):
    request = SocketRequestEventArgs(e._instance)
    print(request.client.end_point, "says", request.message)

server.socket_request(on_request)

server.start(50001)

# ...

server.stop()
##
```

Several robots can connect to the same server: `ConnectedClients` lists them, and each `SocketClient` has its own `SocketWrite`. Allow the port of the server in the firewall of the PC.

## Try it in the demo application

Everything on this page can be tried without writing code, in the **Socket communication** page of the [demo application](/universal-robots/documentation/demo-app).

![Socket communication page of the Universal Robots SDK demo application](/universal-robots/WinformsScreenshots/Socket.jpg)

Its C# source is [SocketControl.cs](https://github.com/underautomation/UniversalRobots.NET/blob/main/UnderAutomation.UniversalRobots.Showcase.Forms/Components/SocketControl.cs).

## Reference

**Members of SocketCommunication.Internal.SocketCommunicationServerBase**
```csharp
public class SocketCommunicationServerBase : URServiceBase, ISocketHandler {
    public SocketCommunicationServerBase()

    // List of all connected clients. One robot can open multiple sockets.
    public SocketClient[] ConnectedClients { get; }

    // Is the socket server enabled
    public bool Enabled { get; }

    // Socket server local port
    public int Port { get; }

    // Event raised when a robot connects with URScript function socket_open()
    public event SocketCommunicationServerBase.SocketClientConnectionEventHandler SocketClientConnection

    // Event raised when the robot socket disconnects
    public event SocketCommunicationServerBase.SocketClientDisconnectionEventHandler SocketClientDisconnection

    // Event raised when the robot calls socket_get_var()
    public event SocketCommunicationServerBase.SocketGetVarEventHandler SocketGetVar

    // Event raised when a message is received from robot
    public event SocketCommunicationServerBase.SocketRequestEventHandler SocketRequest

    // Write a socket message to the robot. The robot should be connected with socket_open()
    public void SocketWrite(string message)

    // Starts socket server. Robot can connect with URScript function socket_open()
    public void Start(int port)

    // Disable local socket server and disconnect all connected clients
    public void Stop()
}
```

**Members of SocketCommunication.SocketClient**
```csharp
public class SocketClient : ISocketHandler {
    // Indicates that robot socket is still active
    public bool Connected { get; }

    // Closes socket communication to robot
    public void Disconnect()

    // IP address and remote port used by the robot for socket communication
    public readonly IPEndPoint EndPoint

    // Event handler when the robot socket disconnects
    public event SocketCommunicationServerBase.SocketClientDisconnectionEventHandler SocketClientDisconnection

    // Event raised when the robot calls socket_get_var()
    public event SocketCommunicationServerBase.SocketGetVarEventHandler SocketGetVar

    // Event raised when a message is received from robot
    public event SocketCommunicationServerBase.SocketRequestEventHandler SocketRequest

    // Write a socket message to the robot. The robot should be connected with socket_open()
    public void SocketWrite(string message)

    // Returns the remote endpoint address and port of the connected robot.
    public override string ToString()
}
```

**Members of SocketCommunication.SocketClientConnectionEventArgs**
```csharp
public class SocketClientConnectionEventArgs : EventArgs {
    // Robot remote endpoint
    public readonly SocketClient Client
}
```

**Members of SocketCommunication.SocketRequestEventArgs**
```csharp
public class SocketRequestEventArgs : EventArgs {
    // Robot IP information
    public readonly SocketClient Client

    // Message content received from robot
    public readonly string Message
}
```

**Members of SocketCommunication.SocketGetVarEventArgs**
```csharp
public class SocketGetVarEventArgs : EventArgs {
    // Robot remote endpoint
    public readonly SocketClient Client

    // Name of requested variable
    public readonly string Name

    // Variable value to send to the robot. If value is null, no messsage is replied to the robot
    public int? Value
}
```

**Members of SocketCommunication.SocketClientDisconnectionEventArgs**
```csharp
public class SocketClientDisconnectionEventArgs : EventArgs {
    // Robot remote endpoint
    public readonly SocketClient Client
}
```

## What to read next

- [XML-RPC](/universal-robots/documentation/xml-rpc): the robot program calls a function of the PC and waits for its answer.
- [Read and write registers](/universal-robots/documentation/registers): exchange numbers without a server.