Overview
It was discussed on the call that this feature will be confirmed with the internal team for a release in November, and the version will be updated accordingly.
Connection Setup:
Network Requirements:
- The Semi Integration application will only function on the terminals with Ethernet and Wi-Fi.
Enable the Connection Type:
- Enable the connection type in the portal for the EPI which is going to load in the Terminal.
- Portal -> Device Management -> EPI -> Edit Parameter -> Terminal & Transaction -> Integration -> Enable the POS Integration -> Select the Connection Type -> Save the changes.
FOR WEB SOCKET:
FOR TCP:
- Take the Param download in the Terminal.
Server Connection:
- To connect to the server, the application will display the message:
“Server is Waiting for Transaction” - This indicates that the server is ready and waiting for a request from the client.
Client Configuration:
- Users must enter the following information in the client software application:
IP Address: [Enter the server's IP address here]
Port Value: 5000 - Ensure that the IP address entered is the same on both the system and the terminal.
For WebSocket connections, the following sample IP:
For TCP connections, the following sample IP:
Network Considerations:
- For successful connection, both the system and the terminal must be connected to the same network (either the same hotspot or Wi-Fi).
Sample Code
#include "ws.h" // WebSocket server header file
#include <stdio.h>
#include <string.h>
#define MAX_MSG_SIZE 1024 // Maximum message size
#define PORT 8080 // The port the WebSocket server will listen on
// Callback function when a new WebSocket connection is opened
void on_open(struct ws_connection *conn) {
printf("New WebSocket connection opened.\n");
const char *jsonMsg = {"TRAN_MODE": "1", "TRAN_CODE": "1", "AMOUNT": "100"};
// Send the JSON message to the client
ws_send_message(conn, jsonMsg, strlen(jsonMsg)); // Send the message
}
// Callback function to handle incoming messages from the client
void on_message(struct ws_connection *conn, const char *message, size_t len) {
char buffer[MAX_MSG_SIZE];
// Print the message received from the client
printf("Received message: %.*s\n", (int)len, message);
// Prepare an acknowledgment message
snprintf(buffer, MAX_MSG_SIZE, "Server received your message: %.*s", (int)len, message);
// Send acknowledgment message back to the client
ws_send_message(conn, buffer, strlen(buffer));
}
// Callback function when the WebSocket connection is closed
void on_close(struct ws_connection *conn) {
printf("WebSocket connection closed.\n");
}
// Main function to initialize and run the WebSocket server
int main() {
// Step 1: Initialize the WebSocket server configuration
struct ws_server server;
server.port = PORT; // Set the WebSocket server's port
server.on_open = on_open; // Set callback for new connections
server.on_message = on_message; // Set callback for incoming messages
server.on_close = on_close; // Set callback for closed connections
// Step 2: Initialize the WebSocket server
if (ws_init(&server) != 0) {
fprintf(stderr, "Failed to initialize WebSocket server on port %d\n", PORT);
return -1; // Exit if initialization fails
}
printf("WebSocket server running on port %d\n", PORT);
// Step 3: Run the WebSocket server's event loop
ws_run(&server);
// Step 4: Clean up resources when the server shuts down
ws_cleanup(&server);
return 0;
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Net.WebSockets;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Enable WebSocket support in the app
app.UseWebSockets();
// WebSocket endpoint handling
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
// Accept the WebSocket connection
using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
Console.WriteLine("WebSocket connection established");
// Send a welcome message
var chMsg = Encoding.UTF8.GetBytes("Welcome to the WebSocket server!");
await webSocket.SendAsync(
new ArraySegment<byte>(chMsg),
WebSocketMessageType.Text,
true,
CancellationToken.None);
// Handle receiving messages from the client
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
// Echo the received message back to the client
var receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received: {receivedMessage}");
var serverResponse = $"Server received your message: {receivedMessage}";
var responseBytes = Encoding.UTF8.GetBytes(serverResponse);
await webSocket.SendAsync(
new ArraySegment<byte>(responseBytes),
WebSocketMessageType.Text,
true,
CancellationToken.None);
// Continue to receive the next message
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
// Close the WebSocket connection when done
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
Console.WriteLine("WebSocket connection closed");
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
app.Run();
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
"log"
)
const (
port = ":8080" // The port the WebSocket server will listen on
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// Handler function for WebSocket connections
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal("Error upgrading connection:", err)
return
}
defer conn.Close()
onOpen(conn)
for {
messageType, msg, err := conn.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
break
}
onMessage(conn, messageType, msg)
// Echo back the message for demonstration purposes
if err := conn.WriteMessage(messageType, msg); err != nil {
log.Println("Error writing message:", err)
break
}
}
onClose(conn)
}
// Callback function when a new WebSocket connection is opened
func onOpen(conn *websocket.Conn) {
fmt.Println("New WebSocket connection opened.")
// Prepare the JSON message
jsonMsg := `{
"TRAN_MODE": "1",
"TRAN_CODE": "1",
"AMOUNT": "100"
}`
// Send the JSON message to the client
conn.WriteMessage(websocket.TextMessage, []byte(jsonMsg)) // Send the message
}
// Callback function to handle incoming messages from the client
func onMessage(conn *websocket.Conn, messageType int, message []byte) {
fmt.Printf("Received message: %s\n", message)
// Prepare an acknowledgment message
ackMessage := fmt.Sprintf("Server received your message: %s", message)
conn.WriteMessage(messageType, []byte(ackMessage)) // Send acknowledgment message back to the client
}
// Callback function when the WebSocket connection is closed
func onClose(conn *websocket.Conn) {
fmt.Println("WebSocket connection closed.")
}
// Main function to start the WebSocket server
func main() {
http.HandleFunc("/ws", wsHandler) // Handle WebSocket connections at /ws
fmt.Println("WebSocket server running on port 8080")
if err := http.ListenAndServe(port, nil); err != nil {
log.Fatal("Error starting server:", err)
}
}
// Import the 'ws' WebSocket library
const WebSocket = require('ws');
// Define the port for the WebSocket server
const PORT = 8080;
// Create a WebSocket server instance
const wss = new WebSocket.Server({ port: PORT });
// When a client connects to the server
wss.on('connection', (ws) => {
console.log('New client connected');
// Prepare the JSON message
const jsonMessage = JSON.stringify({
"TRAN_MODE": "1",
"TRAN_CODE": "1",
"AMOUNT": "100"
});
// Send the JSON message to the connected client
ws.send(jsonMessage);
console.log(`Sent: ${jsonMessage}`);
// When a message is received from a client
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Send a response message back to the client
const responseMessage = `Server received your message: ${message}`;
ws.send(responseMessage);
console.log(`Sent: ${responseMessage}`);
});
// When the client disconnects
ws.on('close', () => {
console.log('Client has disconnected');
});
});
// Start the server
console.log(`WebSocket server is running on ws://localhost:${PORT}`);
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class MyWebSocketServer implements MessageComponentInterface {
// When a new connection is established
public function onOpen(ConnectionInterface $conn) {
echo "New connection! ({$conn->resourceId})\n";
// Prepare the JSON message
$jsonMsg = json_encode([
"TRAN_MODE" => "1",
"TRAN_CODE" => "1",
"AMOUNT" => "100"
]);
// Send the JSON message to the client
$conn->send($jsonMsg);
echo "Sent: {$jsonMsg}\n";
}
// When a message is received from a client
public function onMessage(ConnectionInterface $from, $msg) {
echo "Received message: {$msg}\n";
// Prepare and send a response message (echo the client's message with acknowledgment)
$response = "Server received your message: {$msg}";
$from->send($response);
}
// When the connection is closed
public function onClose(ConnectionInterface $conn) {
echo "Connection {$conn->resourceId} has disconnected\n";
}
// In case of an error on the connection
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
// Run the WebSocket server
$server = \Ratchet\Server\IoServer::factory(
new \Ratchet\Http\HttpServer(
new \Ratchet\WebSocket\WsServer(
new MyWebSocketServer()
)
),
8080 // The port the server listens on
);
// Start the server
$server->run();
import asyncio
import websockets
import json # Import json module for sending JSON messages
# Define the port for the WebSocket server
PORT = 8080
# Function to handle incoming WebSocket messages and send responses
async def handle_connection(websocket, path):
# Prepare the JSON message
json_message = json.dumps({
"TRAN_MODE": "1",
"TRAN_CODE": "1",
"AMOUNT": "100"
})
# Send the JSON message when a client connects
await websocket.send(json_message)
print(f"Sent: {json_message}")
try:
async for message in websocket:
# Print the message received from the client
print(f"Received: {message}")
# Prepare a response message (echo the client's message with acknowledgment)
response = f"Server received your message: {message}"
await websocket.send(response)
print(f"Sent: {response}")
except websockets.exceptions.ConnectionClosed:
print("Connection closed by client")
# Main function to start the WebSocket server
async def main():
print(f"WebSocket server running on port {PORT}")
# Start the WebSocket server
async with websockets.serve(handle_connection, "localhost", PORT):
await asyncio.Future() # Run forever
# Start the asyncio event loop to run the server
if __name__ == "__main__":
asyncio.run(main())
require 'faye/websocket'
require 'eventmachine'
require 'json'
class WebSocketServer
def initialize(port)
@port = port
end
def start
puts "WebSocket server running on port #{@port}"
EM.run do
EM.start_server '0.0.0.0', @port, WebSocketConnection
end
end
end
class WebSocketConnection
def initialize(ws)
@ws = ws
on_open
end
def on_open
puts "New WebSocket connection opened."
# Prepare the JSON message with the required fields
initial_message = {
TRAN_MODE: "1",
TRAN_CODE: "1",
AMOUNT: "100"
}
# Send the initial JSON message to the client
@ws.send(initial_message.to_json) # Send the JSON message
end
def receive_message(message)
puts "Received message: #{message}"
# Prepare acknowledgment message
response_message = { message: "Server received your message: #{message}" }
# Send acknowledgment message back to the client
@ws.send(response_message.to_json)
end
def on_close
puts "WebSocket connection closed."
end
end
# Starting the server on port 8080
port = 8080
server = WebSocketServer.new(port)
server.start
Option Explicit
Dim WithEvents ws As WebSocketX.WebSocket
Private Sub Form_Load()
btnDisconnect.Enabled = False
' VB controls need Charset to properly work with Unicode
Me.Font.Charset = 161
Set txtMessage.Font = Me.Font
Set txtOutput.Font = Me.Font
' Create WebSocketX instance
Set ws = New WebSocketX.WebSocket
' Set WebSocket text mode and IO buffers
ws.TextMode = True
ws.MaximumIncomingMessageSizeBytes = 1000000#
ws.WriteBufferSizeBytes = 1000000#
End Sub
Private Sub btnConnect_Click()
txtOutput.Text = "Connecting ..."
btnDisconnect.Enabled = True
' Connect to WebSocket Echo Server in insecure mode
ws.Open txtServerURL.Text, WEBSOCKET_SECURITY_ENUM.INSEURE
End Sub
Private Sub btnDisconnect_Click()
txtOutput.Text = "Disconnecting ..."
btnConnect.Enabled = True
btnDisconnect.Enabled = False
' Disconnect from server and transmit closing frame
ws.Close CLOSE_CODE_NORMAL
End Sub
Private Sub ws_OnOpen()
txtOutput.Text = "Connected."
End Sub
Private Sub ws_OnError(ByVal ErrorCode As Long, ByVal ErrorDescription As String)
txtOutput.Text = "ERROR: " & ErrorCode & ", " & ErrorDescription
End Sub
Private Sub ws_OnClose()
txtOutput.Text = "Disconnected."
End Sub
Private Sub ws_OnMessage(ByVal data As String)
txtOutput.Text = txtOutput.Text + vbCrLf + data
End Sub
' Updated button click event to send JSON message
Private Sub btnSendMessage_Click()
Dim jsonMessage As String
' Create the JSON message
jsonMessage = "{""TRAN_MODE"": ""1"", ""TRAN_CODE"": ""1"", ""AMOUNT"": ""100""}"
If ws.State <> WS_OPEN Then
MsgBox "Please connect to WebSocket echo server", vbCritical
Exit Sub
End If
' Send the JSON formatted message
ws.Send jsonMessage
End Sub
Payloads
- Can implement the code in any language but at last Terminal will expect the request in the form of cJson only.
- The sample request formats attached with the collections which is terminal expected. Use postman app to test all the transactions payloads by updating the shared collections if need